What exactly does .class return in Java?

Why is it not allowed to call a static method through the class reference returned by .class ? But instead, if the static method is called directly using the class name, it works fine. As in the 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();
    }
}

      

+3


source to share


3 answers


.class

returns an instance of the class java.lang.Class

- and no is Class<Base>

not the same as Base

.



The class java.lang.Class

is mainly used when you are using the reflection API .

+5


source


b

is of type Class

, so it has methods of type Class , not methods of your Base

class.



You can use instances Class

to call methods of the classes they reference through reflection.

+3


source


Base

is the name of the class. Base.method()

is the java syntax for calling a static method in a class Base

.

Base.class

is a reference to an object of the type Class

that describes the class Base

. Base.class.method1()

doesn't work, of course, because the class Class

doesn't have a method method1

.

You can call the methods of the base class if you need using reflection. Consider:

Base.class.getMethod("method1").invoke(null);

+1


source







All Articles