user632942
user632942

Reputation: 483

What is class property of an object point to - MyClass.class

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

Answers (3)

Raedwald
Raedwald

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

Pragmateek
Pragmateek

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

thomasd
thomasd

Reputation: 2612

An instance of the class Class.

http://javadocs.org/class

Upvotes: 1

Related Questions