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();
}
}
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With