尝试通过 Class.forName
激活类的方法时出现问题。
班级:
public class example{
private int number;
static {
System.out.println("example initializing");
}
example(int number) {
this.number = number;
}
public void printFunc() {
System.out.println("Hello World");
}
}
public class Main {
public static void main(String[] args) {
Class<?> oc = Class.forName("example");
oc.printFunc(); //doesnt work
}
}
问题: 打印了 static
初始化,但是,当尝试激活 printFunc
时,出现错误:printFunc is undefined for the type Class<capture#5-of ?>
问题:如何通过 Class
激活 Class.forName
的功能?
答案 0 :(得分:2)
使用反射中的 method invocation:
try {
Class<?> exampleClass = Class.forName("example");
Object exampleObject = exampleClass.newInstance();
Method printFunctionMethod = exampleObject.getClass().getMethod("printFunc");
printFunctionMethod.invoke(exampleObject);
}
catch (Exception e) {}