In java, what is the need/use of ".class" property of an object. e.g., MyClass.class. What does .class point to.
Asked
Active
Viewed 74 times
3 Answers
1
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());

Pragmateek
- 13,174
- 9
- 74
- 108
0
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.

Raedwald
- 46,613
- 43
- 151
- 237
-
What is the use of any "interface.class" property in java ? – 9me Jan 25 '20 at 12:09