Reputation: 2640
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
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
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