If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()
Foo foo=new Foo();
Class c = foo.getClass();
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 = boolean.class;
and this would produce compile-time error
Class c = b.getClass();
because a boolean is a primitive type and cannot be dereferenced
And for something like this
Foo foo=null;
note that you cannot use foo.getClass()
in this case since it is not instantiated.
And finally for something like this
Foo foo=new FooChild();
Class c= foo.getClass(); //returns FooChild, evaluates at runtime
Class c= Foo.class;// returns Foo , evaluates statistically at compile-time.
Edit:- For .class
its a static field inside every primitive type, static Class<Integer>
,The Class instance representing the Integer. you can see it here for Integer , here for Boolean. boolean, byte, char, short, int, long, float, and double all of them have a Class static field because like i said its always going to stay same and primitive types cannot be cannot be dereferenced. To see the source, if you see source of Integer you can see the class field as public static final Class<Integer> TYPE = (Class<Integer>) VMClassLoader.getPrimitiveClass('I');
, see here line 82. You can search and see for others too.