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?
SomeClass.class
returns a Java Class object. Class is genericized, so the actual type of SomeClass.class will be Class<SomeType> .
There are lots of uses for this object, and you can read the Javadoc for it here: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html
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.
The Class class, which is different from the class keyword, is meta-data describing instances. It tells you about the methods, data members, constructors, and other features of the instances that you create by calling new.
For example get(ClientResponse.class) method takes the
ClientResponse.class how does it uses this when it gets it and what
are the advantage over just passing a instance of it?
You can't pass an instance of ClientResponse to this method; it's expecting meta-data about all instances of ClientResponse. If you passed an instance, you'd expect that the method might change the state of that instance. But passing the meta-data about all instances might allow the method to create a new kind of instance (e.g. a dynamic proxy) or do something else that depends on the meta-data about all instances of ClientResponse. See the difference?
A class is a "blueprint" of the object. The instance is a object.
If we have
public class SomeClass {
int a;
SomeClass(int a) {
this.a = a
}
}
We can have an instance of this class
SomeClass c = new SomeClass(10);
c is an instance of the class. It has a integer a with value 10.
The object SomeClass.class represents a Class.
Here SomeClass.class is a object of the type Class which has the information that SomeClass is
a concrete class with
one constructor
with a integer member variable
and lots more other metadata about the class SomeClass. Note that it does not have a value for a.
You should use get(c) incase you are planning to do something with a instance of c like call c.a or other useful functions to manupulate/get data of the instance.
You should use get(SomeClass.class) when the get returns something based on the fact that the argument is some type of class. For example, if this is a method on a Registry class which has a map which retrieves a implementation class based on type of class passed in.
The very most important fact is - you don't need to have an instance to call the method. It's critically useful in situations when you cannot for some reason instantiate a class, e.g. it's abstract, or have only private constructor, or can only be correctly instantiated by some framework, like Spring or JSF.
You can then call get to obtain an object of a requested type without even knowing where it does come from and how it get's created.
Here ClientResponse.class is an instance of Class<ClientResponse>. In general Class object represents type of an object. When you create new instance:
Object obj = new ClientResponse()
you can retrieve the class (type) of that object by calling:
obj.getClass()
So, why would you pass Class objects around? It's less common, but one reason is to allow some method create arbitrary number of instances of a given class:
ClientResponse resp = ClientResponse.newInstance();
There's a lot of ways Class objects can be used. This is used for Reflection. Below is a link that can help you understand more.
http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code. Since this field is public and static, we can access it using dotted notation along with class name as in your case it is ClientResponse.class.
Related
If I'm only given a field instance from a class, without further knowledge about the class that declares that field, is it possible to get an instance of the declaring (outer) class?
For instance, consider the following class structure.
class A {
static final Tclass t = Tclass.create();
}
Now, in some other function, we are only given t (Tclass instance). Is it possible to use reflection in some way to grab the outer/declaring class (class A) that holds t?
I don't think the statement given t means what you think it means.
If you mean you do something like
someMethod(t);
and you want someMethod to get a reference back to A, you're out of luck. When used in an expression like that, the expression t resolves to a value. That value is a reference to an object. Such a reference is one-way only. someMethod has absolutely no knowledge about the existence of a static variable t.
If you mean you have a Field instance for t, you can simply call Field#getDeclaringClass() to get the declaring class.
What does .class mean in Java? For example, if I created a class called Print. What does Print.class return?
When you write .class after a class name, it references the class literal -
java.lang.Class object that represents information about a given class.
For example, if your class is Print, then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
.class is used when there isn't an instance of the class available.
.getClass() is used when there is an instance of the class available.
object.getClass() returns the class of the given object.
For example:
String string = "hello";
System.out.println(string.getClass().toString());
This will output:
class java.lang.String
This is the class of the string object :)
Just to clarify, this '.class' method is not referring to the bytecode file you see after compiling java code nor a confusion between the concepts of Class vs. Object in OOP theory.
This '.class' method is used in Java for code Reflection. Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields, etc, etc.
Check these links (already mentioned above) to get all the details:
https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html
Normally you don't plan on using Reflection right away when you start building your project. It's something that you know you need after trying to manage already working code. Many times you need it to manage multiple instances of your program. Maybe you want to identify each particular 'clone' to determine if something is already defined, or count the number of functions, or just simply log the details of a particular instance of your class.
If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()
The .class Syntax
If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.
boolean b;
Class c = b.getClass(); // compile-time error
Class c = boolean.class; // correct
See: docs.oracle.com about class
If there is no instance available then .class syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object. Since, there is no instance of primitive data type, we have to use .class syntax for primitive data types.
package test;
public class Test {
public static void main(String[] args)
{
//there is no instance available for class Test, so use Test.class
System.out.println("Test.class.getName() ::: " + Test.class.getName());
// Now create an instance of class Test use getClass()
Test testObj = new Test();
System.out.println("testObj.getClass().getName() ::: " + testObj.getClass().getName());
//For primitive type
System.out.println("boolean.class.getName() ::: " + boolean.class.getName());
System.out.println("int.class.getName() ::: " + int.class.getName());
System.out.println("char.class.getName() ::: " + char.class.getName());
System.out.println("long.class.getName() ::: " + long.class.getName());
}
}
I think the key here is understanding the difference between a Class and an Object. An Object is an instance of a Class. But in a fully object-oriented language, a Class is also an Object. So calling .class gets the reference to the Class object of that Class, which can then be manipulated.
Adding to the above answers:
Suppose you have a a class named "myPackage.MyClass". Assuming that is in classpath, the following statements are equivalent.
//checking class name using string comparison, only Runtime check possible
if(myInstance.getClass().getName().equals(Class.forName("myPackage.MyClass")).getName()){}
//checking actual Class object for equality, only Runtime check possible
if(myInstance.getClass().getName() == Class.forName("myPackage.MyClass"))){}
//checking actual Class object for equality, but compile time validation
//will ensure MyClass is in classpath. Hence this approach is better (according to fail-fast paradigm)
if(myInstance.getClass() == MyClass.class){}
Similarly, the following are also equivalent.
Class<?> myClassObject = MyClass.class; //compile time check
Class<?> myClassObject = Class.forname("myPackage.MyClass"); //only runtime check
If JVM loads a type, a class object representing that type will be present in JVM. we can get the metadata regarding the type from that class object which is used very much in reflection package. MyClass.class is a shorthand method which actually points to the Class object representing MyClass.
As an addendum, some information about Class<?> reference which will be useful to read along with this as most of the time, they are used together.
Class<?> reference type can hold any Class object which represents any type.
This works in a similar fashion if the Class<?> reference is in method argument as well.
Please note that the class "Class" does not have a public constructor. So you cannot instantiate "Class" instances with "new" operator.
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
One of the changes in JDK 5.0 is that the class java.lang.Class is generic, java.lang.Class Class<T>, therefore:
Class<Print> p = Print.class;
References here:
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
http://docs.oracle.com/javase/tutorial/extra/generics/literals.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2
It's not hard to understand String.class.getClass(), which mean return a Class Object that represent the run time class of String Object. But what's going on when calling Class.class.getClass(), can I apprehend it as returning a Class object that represent the run time class of Class object itself? How can this be implemented in Java reflection API?
a Class object that represent the run time class of Class object itself?
Yes.
But String.class.getClass() is the same thing.
String.class already means "the object of type Class that represents the String class". Calling .getClass() on that means "the object of type Class that represents the Class class", because we're calling it on an object of type Class.
If you have an object that is a String, for example "hi mom", then you can reflect it with .getClass(): ("hi mom").getClass() for example. IIRC, this will return the exact same object as String.class in normal circumstances, because there is only one Class object per class (, per ClassLoader in use).
How can this be implemented in Java reflection API?
Every time the bytecode for a class is loaded, a Class object is created and associated with that bytecode. Every object conceptually keeps a "hidden" reference to the Class instance that represents its class, that is automatically set by the constructor. Class objects have this reference set to a Class object that represents the Class class. In particular, the Class object that represents the Class class has a reference to itself.
can I apprehend it as returning a Class object that represent the run time class of Class object itself?
No. Object.class.getClass() is same as Class.class.getClass().
System.out.println(Object.class.getClass() == Class.class.getClass()); // true
Is there any way in Java to store a reference to a class? Here's what I want to do:
public class Foo
{
public static void doSomething() {...}
};
SomeClass obj = Foo;
obj.doSomething();
Is there some class "SomeClass" which lets me store a reference to a class, such that I can later use that stored object to call a static member of the original class?
The obvious thing would be class Class:
Class obj = Foo.class;
obj.someMember().doSomething();
but I haven't figured out which of class Class's members might act as "someMember()"... none of them, I think.
Does anyone know if what I'm trying to do is possible in Java?
You can dynamically get a method from a Class object using the getMethod() methods on the class. If a method is static, then the "object" parameter of "invoke" will be null.
For example, the "obj.someMember()" above would be something like this:
obj.getMethod("someMember", null).invoke(null, null);
The extra nulls are because your method requires no parameters. If your method takes parameters, then they will need to be passed in accordingly.
This will throw various checked exceptions, so you'll need to handle those as well.
Once you've invoked the method, it will return an Object. You'll want to cast that to whatever type you're expecting, and then you'll be able to run the "doSomething()" method directly on that.
This is using a trick called reflection, if you'd like to read up more on it. :)
If you are using jdk1.5 or above, annotation will be a choice when you want to get metadata of Class.
I'm beginning to program in Java.
public static void main(String[]args)
A book said that I should use static in this case, but doesn't clearly say why I should or what it means.
Could you clarify this?
The concept of static has to do with whether something is part of a class or an object (instance).
In the case of the main method which is declared as static, it says that the main method is an class method -- a method that is part of a class, not part of an object. This means that another class could call a class method of another class, by referring to the ClassName.method. For example, invoking the run method of MyClass would be accomplished by:
MyClass.main(new String[]{"parameter1", "parameter2"});
On the other hand, a method or field without the static modifier means that it is part of an object (or also called "instance") and not a part of a class. It is referred to by the name of the specific object to which the method or field belongs to, rather than the class name:
MyClass c1 = new MyClass();
c1.getInfo() // "getInfo" is an instance method of the object "c1"
As each instance could have different values, the values of a method or field with the same name in different objects don't necessarily have to be the same:
MyClass c1 = getAnotherInstance();
MyClass c2 = getAnotherInstance();
c1.value // The field "value" for "c1" contains 10.
c2.value // The field "value" for "c2" contains 12.
// Because "c1" and "c2" are different instances, and
// "value" is an instance field, they can contain different
// values.
Combining the two concepts of instance and class variables. Let's say we declare a new class which contains both instance and class variables and methods:
class AnotherClass {
private int instanceVariable;
private static int classVariable = 42;
public int getInstanceVariable() {
return instanceVariable;
}
public static int getClassVariable() {
return classVariable;
}
public AnotherClass(int i) {
instanceVariable = i;
}
}
The above class has an instance variable instanceVariable, and a class variable classVariable which is declared with a static modifier. Similarly, there is a instance and class method to retrieve the values.
The constructor for the instance takes a value to assign to the instance variable as the argument. The class variable is initialized to be 42 and never changed.
Let's actually use the above class and see what happens:
AnotherClass ac1 = new AnotherClass(10);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
Notice the different ways the class and instance methods are called. The way they refer to the class by the name AnotherClass, or the instance by the name ac1. Let's go further and see the behavioral differences of the methods:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
AnotherClass.getClassVariable(); // Returns "42"
As can be seen, an instance variable is one that is held by an object (or "instance"), therefore unique to that particular instance, which in this example is the objects referred to by ac1 and ac2.
A class variable on the other hand is only unique to that entire class. To get this point across even better, let's add a new method to the AnotherClass:
public int getClassVariableFromInstance() {
return classVariable;
}
Then, run the following:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
ac1.getClassVariableFromInstance(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
ac2.getClassVariableFromInstance(); // Returns "42"
Although getClassVariableFromInstance is an instance method, as can be seen by being invoked by referring to the instances ac1 and ac2, they both return the same value, 42. This is because in both instance methods, they refer to the class method classVariable which is unique to the class, not to the instance -- there is only a single copy of classVariable for the class AnotherClass.
I hope that some what clarifies what the static modifier is used for.
The Java Tutorials from Sun has a section called Understanding Instance and Class Members, which also goes into the two types of variables and methods.
Please see a nice description on Wikipedia
For example, notice how in the Math class, you can say things like
Math.Abs(x);
without having to say
Math m = new Math();
These are static methods since you don't need an instance. Instance methods are those methods that require you to have an instance of a class.
Employee e = new Employee();
e.Terminate();
A static method is one that applies to the class a whole, not any particular member. .goExtinct() would be a method of the Duck population as a whole, not any particular duck. main is public and static because is has to always be available, and its not part of any particular class.
Usually, you have to have an object, an instance of a class, in order to call methods on it, for at least two reasons:
It depends on the object which class implements the method that is being called. For example if you have an instance of a subclass, the method in the subclass will be called instead, even though the code that calls the method is the same.
Objects usually have internal state (fields), that methods can refer to. This does not work if there is no object instance.
You create object instances by calling the class' constructor:
MyObject a = new MyObject();
Static methods are methods that are not attached to object instances. They can be called by just naming the class. As a result of this they
cannot be dynamically dispatched to subclasses (which is why you get a warning when you try to call it on object instances, that is just confusing syntax)
they cannot refer to instance state (non-static fields and other non-static methods).
Many people consider static methods a bad design pattern, and advise to not use them (except for public static void main) Look up the singleton instance pattern for an alternative.
In this particular case the main method must be static, because of the way the JVM will start loading classes and creating objects. When you start a Java program the JVM will look for the definition of the class that was passed to it and load it. So java MyClass will result in loading the definition of the MyClass class.
By definition a Java program will start executing in the main() method of the class that was passed to the JVM as the class to load initially. At this point in time no instance (object) of type MyClass has been created, so the main method has to be static to allow the start of the execution of your program.
If you want to see which classes are being loaded during the execution of a Java program you can use the -verbose:class command line option.
In any object oriented programming language like Java or C++ you create classes which at the very basic level are like BluePrints of a building. You can look at a blueprint and determine how various components are connected but you cannot actually live in it. It's the same with classes and object. Classes are blueprint and you create an instance of a class which is called an Object. For the same blueprint you can have multiple buildings , same way for one class you can have multiple objects. An Object is an instance of a class. Each method in a class can be called on an Object or an instance of a class, whereas for calling static methods you actually don't need an instance, you can directly call ClassName.method() without actually creating an instance of a class.
There will be times when you will want to define a class member that will be used independently of any object of that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
The two types of static members are static fields and static methods:
Static field:
A field that’s declared with the static keyword, like this:
private static int ballCount:
The position of the static keyword is interchangeable with the positions of the visibility keywords (private and public, as well as protected). As a result, the following statement works, too:
static private int ballCount;
As a convention, most programmers tend to put the visibility keyword first.
The value of a static field is the same across all instances of the class. In other words, if a class has a static field named CompanyName, all objects created from the class will have the same value for CompanyName.
Static fields are created and initialized when the class is first loaded. That happens when a static member of the class is referred to or when an instance of the class is created, whichever comes first.
Static method:
A method declared with the static keyword. Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.
The best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.
One of the basic rules of working with static methods is that you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields.