Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is .class a method or field?

Tags:

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")); 
like image 527
Adam Lee Avatar asked Jan 12 '12 14:01

Adam Lee


People also ask

What is class and field method?

A field is a member variable that belongs to a class. A method is a set of java commands referred to by name. You are able to execute all the commands by using the name of the method. Methods can take values as parameters and return a value as a result.

What does .class mean in java?

What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.

What is a method field?

The Method field in HTTP indicates the method to be performed on the object identified by the URL. The method GET below is always supported, The list of other methods acceptable by the object are returned in response to either of these two requests.

Why is .class method used in java?

A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).


2 Answers

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

like image 173
SLaks Avatar answered Jan 18 '23 14:01

SLaks


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()); 
like image 42
Vibha Sanskrityayan Avatar answered Jan 18 '23 14:01

Vibha Sanskrityayan