Reputation: 471
What does .class
mean in, for example, MyClass.class
? I understand that when you put the name of a class and the point it is used to access its static fields or methods, but that doesn't relate to '.class'
Upvotes: 46
Views: 19399
Reputation: 22692
You can add .class
to the name of any class to retrieve an instance of its Class object.
When you use Integer.class
you reference an instance of Class<Integer>
, which is a typed class object.
I always thought this was a field member that got added by the compiler, but it looks like it's really just syntactic sugar.
Upvotes: 7
Reputation: 12408
When you write .class
after a class name, it references the Class
object that represents the given class (formally, it is a named class literal). The the type of NombreClase.class
is Class<NombreClase>
.
E.g., NombreClase.class
is an object that represents the class NombreClase
on runtime. It is the same object that is returned by the getClass()
method of any (direct) instance of NombreClase
.
NombreClase obj = new NombreClase();
System.out.println(NombreClase.class.getName());
System.out.println(obj.getClass().getName())
Upvotes: 12
Reputation: 36940
SomeClass.class
gets the Class<SomeClass>
type which you can use for programming using the reflection API.
You can get the same type if you have an instance of the class using instance.getClass()
.
You can check out the documentation here. For example, you can:
Upvotes: 23