为什么不允许通过.class返回的类引用调用静态方法?但是如果直接使用类名调用静态方法,则可以正常工作。就像下面的示例一样。它们不相等吗?
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();
}
}
java.lang.Class
和类型typeinfo.Base
。正如Eran所说,类型为Class<Base>
的对象具有Class
类的方法,而不是Base
类的方法,因此您无法在类型为Class
的对象上调用Base
类的方法。 - Jesper