Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is returned by .class in Java?

Tags:

java

class

Why is it not allowed to call the static method through the class reference returned by .class ? But instead if static method is called directly using class name it works fine. Like in example below. Are they not equal ?

package typeinfo;

class Base {
    public static void method1() {
        System.out.println("Inside static method1");
    }
    public void method2() {
        System.out.println("Inside method2");
    }
}
public class Sample {
    public static void main(String[] args) {
        Class<Base> b = Base.class;
        // Works fine
        Base.method1();
        // Gives compilation error: cannot find symbol
        // Is below statement not equal to Base.method1() ?
        b.method1();
    }
}
like image 835
niting112 Avatar asked Apr 30 '26 08:04

niting112


1 Answers

.class returns an instance of class java.lang.Class - and no, Class<Base> is not the same as Base.

Class java.lang.Class is mainly used when you use the Reflection API.

like image 183
Jesper Avatar answered May 02 '26 22:05

Jesper