Reputation: 483
In java, what is the need/use of ".class" property of an object. e.g., MyClass.class. What does .class point to.
Upvotes: 1
Views: 78
Reputation: 48654
It can be useful in some circumstances where you want to say 'any object of a particular class'. For example, in JUnit you use the class object of a class to indicate that a test is expected to throw an exception of a particular class.
They can also be useful in some advanced uses of generics, to ensure that methods are applicable only to objects of a particular type. For example, Spring HttpMessageConverter
objects use them.
Upvotes: 0
Reputation: 13364
Sometimes you need some typing information, e.g. when you do some reflection.
The .class is specially handled by the compiler and is interpreted as a Class instance.
If you've used C# before this is the equivalent of the typeof operator.
e.g. if you want to dynamically get the full name of a type you can do:
System.out.println(String.class.getName());
Upvotes: 1