I don't really understand how the class
keywords work in some instances.
For example, the get(ClientResponse.class)
method takes the ClientResponse.class
. How does it use this when it gets it, and what are the advantages over just passing an instance of it?
The class keyword is used to declare a new Java class, which is a collection of related variables and/or methods. Classes are the basic building blocks of object−oriented programming. A class typically represents some real−world entity such as a geometric Shape or a Person.
In Java, Using predefined class name as Class or Variable name is allowed. However, According to Java Specification Language(§3.9) the basic rule for naming in Java is that you cannot use a keyword as name of a class, name of a variable nor the name of a folder used for package.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
Typically, Java programs that you write will create many different objects from templates known as classes. These objects interact with one another by sending each other messages. The result of a message is a method invocation which performs some action or modifies the state of the receiving object.
In ClientResponse.class
, class
is not a keyword, neither a static field in the class ClientResponse
.
The keyword is the one that we use to define a class in Java. e.g.
public class MyClass { } /* class used here is one of the keywords in Java */
The class
in ClientResponse.class
is a short-cut to the instance of Class<T>
that represents the class ClientResponse
.
There is another way to get to that instance for which you need an instance of ClientResponse
. e.g
ClientResponse obj = new ClientResponse();
Class clazz = obj.getClass();
what are the advantage over just passing a instance of it?
In the above example you can see what would happen in case obj
was null (an NPE). Then there would be no way for the method to get the reference to the Class
instance for ClientResponse
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With