niting112
niting112

Reputation: 2640

What exactly is returned by .class in Java?

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();
    }
}

Upvotes: 3

Views: 78

Answers (3)

Dima
Dima

Reputation: 40500

Base is class name. Base.method() is java syntax for invoking a static method on class Base.

Base.class is a reference to an object of type Class, describing the class Base. Base.class.method1() does not work of course, because class Class does not have a method method1.

You can call methods of underlying class if you have to, using reflection. Consider:

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

Upvotes: 1

Jesper
Jesper

Reputation: 206776

.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.

Upvotes: 5

Eran
Eran

Reputation: 393771

b is of type Class, so it has the methods of the Class type, and not the methods of your Base class.

You can use instances of Class to invoke methods of the classes they refer to via reflection.

Upvotes: 3

Related Questions