Adam Lee
Adam Lee

Reputation: 25778

Is .class a method or field?

Any class in the java has a .class , I want to know .class is a static method or not? Or it is a public static field?

boolean alwaysTrue = (String.class == Class.forName("java.lang.String"));

Upvotes: 23

Views: 18849

Answers (3)

Vibha Sanskrityayan
Vibha Sanskrityayan

Reputation: 1985

When you write .class after a class name, it references the Class object that represents the given class. .class is used when there isn't an instance of the class available.

For example, if your class is Print (it is recommended that class name begin with an uppercase letter), then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.

Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());

Upvotes: 15

Viruzzo
Viruzzo

Reputation: 3025

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2

It's neither. It's an expression evaluated at compile time to the Class object for that class.

Upvotes: 5

SLaks
SLaks

Reputation: 888087

Its neither.
It's a built-in language feature (a class literal) that looks like a public static final field.

Upvotes: 38

Related Questions