1

In java, what is the need/use of ".class" property of an object. e.g., MyClass.class. What does .class point to.

user632942
  • 443
  • 4
  • 8
  • 16

3 Answers3

1

An instance of the class Class.

http://javadocs.org/class

thomasd
  • 2,593
  • 1
  • 22
  • 23
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