What does .class mean in Java?

JavaClassMethods

Java Problem Overview


What does .class mean in Java? For example, if I created a class called Print. What does Print.class return?

Java Solutions


Solution 1 - Java

When you write .class after a class name, it references the class literal - java.lang.Class object that represents information about given class.

For example, if your class is Print, 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());

Solution 2 - Java

.class is used when there isn't an instance of the class available.

.getClass() is used when there is an instance of the class available.

object.getClass() returns the class of the given object.

For example:

String string = "hello";
System.out.println(string.getClass().toString());

This will output:

class java.lang.String

This is the class of the string object :)

Solution 3 - Java

Just to clarify, this '.class' method is not referring to the bytecode file you see after compiling java code nor a confusion between the concepts of Class vs. Object in OOP theory.

This '.class' method is used in Java for code Reflection. Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields, etc, etc.

Check these links (already mentioned above) to get all the details:
https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

Normally you don't plan on using Reflection right away when you start building your project. It's something that you know you need after trying to manage already working code. Many times you need it to manage multiple instances of your program. Maybe you want to identify each particular 'clone' to determine if something is already defined, or count the number of functions, or just simply log the details of a particular instance of your class.

Solution 4 - Java

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()

The .class Syntax

If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

boolean b;
Class c = b.getClass();   // compile-time error

Class c = boolean.class;  // correct

See: docs.oracle.com about class

Solution 5 - Java

If there is no instance available then .class syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object. Since, there is no instance of primitive data type, we have to use .class syntax for primitive data types.

    package test;

    public class Test {
       public static void main(String[] args)
       {
	      //there is no instance available for class Test, so use Test.class
	      System.out.println("Test.class.getName() ::: " + Test.class.getName());
	
	      // Now create an instance of class Test use getClass()
	      Test testObj = new Test();
	      System.out.println("testObj.getClass().getName() ::: " + testObj.getClass().getName());
	
	      //For primitive type
	      System.out.println("boolean.class.getName() ::: " + boolean.class.getName());
	      System.out.println("int.class.getName() ::: " + int.class.getName());
	      System.out.println("char.class.getName() ::: " + char.class.getName());
	      System.out.println("long.class.getName() ::: " + long.class.getName());
       }
    }

Solution 6 - Java

I think the key here is understanding the difference between a Class and an Object. An Object is an instance of a Class. But in a fully object-oriented language, a Class is also an Object. So calling .class gets the reference to the Class object of that Class, which can then be manipulated.

Solution 7 - Java

Adding to the above answers:

Suppose you have a a class named "myPackage.MyClass". Assuming that is in classpath, the following statements are equivalent.

//checking class name using string comparison, only Runtime check possible
if(myInstance.getClass().getName().equals(Class.forName("myPackage.MyClass")).getName()){}

//checking actual Class object for equality, only Runtime check possible
if(myInstance.getClass().getName() == Class.forName("myPackage.MyClass"))){}

//checking actual Class object for equality, but compile time validation
//will ensure MyClass is in classpath. Hence this approach is better (according to fail-fast paradigm)
if(myInstance.getClass() == MyClass.class){}

Similarly, the following are also equivalent.

Class<?> myClassObject = MyClass.class; //compile time check

Class<?> myClassObject = Class.forname("myPackage.MyClass"); //only runtime check

If JVM loads a type, a class object representing that type will be present in JVM. we can get the metadata regarding the type from that class object which is used very much in reflection package. MyClass.class is a shorthand method which actually points to the Class object representing MyClass.

As an addendum, some information about Class reference which will be useful to read along with this as most of the time, they are used together.

Class reference type can hold any Class object which represents any type.

This works in a similar fashion if the Class reference is in method argument as well.

Please note that the class "Class" does not have a public constructor. So you cannot instantiate "Class" instances with "new" operator.

Solution 8 - Java

A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class. One of the changes in JDK 5.0 is that the class java.lang.Class is generic, java.lang.Class Class<T>, therefore:

Class<Print> p = Print.class;

References here:

https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

http://docs.oracle.com/javase/tutorial/extra/generics/literals.html

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuinn WeiView Question on Stackoverflow
Solution 1 - JavaJavierView Answer on Stackoverflow
Solution 2 - JavachristopherView Answer on Stackoverflow
Solution 3 - JavaSalvador ValenciaView Answer on Stackoverflow
Solution 4 - JavaAndrewView Answer on Stackoverflow
Solution 5 - JavaRanjeetView Answer on Stackoverflow
Solution 6 - JavaXerxesView Answer on Stackoverflow
Solution 7 - JavaSRajView Answer on Stackoverflow
Solution 8 - JavaPbxManView Answer on Stackoverflow