从java中的类名实例化类
我试图从类名实例化类,但失败了,我的代码在Processing/Java库中。 我的第一个状态是找到一个好的类,我管理它,但在我发现不可能从类名实例化之后。我需要这样做,因为我的所有方法在我的代码中随处可见,我需要从单个位置的方法中查找信息。 我希望我的目的很明确
我编写了这段代码,但当我通过forName()方法传递名称时,它失败了
控制台返回Unhandled exception type ClassNotFoundException
import java.util.Iterator;
import java.lang.reflect.*;
Target class_a = new Target() ;
Target class_b = new Target() ;
Truc class_c = new Truc() ;
void setup() {
class_a.is(true);
class_b.is(false);
Field [] f = this.getClass().getDeclaredFields();
println("field num:",f.length);
for(int i = 0 ; i < f.length ; i++) {
if(f[i].getType().getName().contains("Target")) {
println("BRAVO it's a good classes");
println("class:",f[i].getClass());
println("name:",f[i].getName());
// I imagine pass the name here to instantiate the class but that's don't work
Class<?> classType = Class.forName(f[i].getName());
// here I try to call method of the selected class
println(classType.get_is());
}
}
}
class Target{
boolean is;
Target() {}
void is(boolean is) {
this.is = is;
}
boolean get_is() {
return is;
}
}
class Truc{
Truc() {}
}
# 1 楼答案
java.lang.Class
对象(通过调用Class.forName
获得)没有方法get_is()
。必须使用反射来调用方法李>但是
get_is()
是非静态的,就不能从类中调用它,即使是通过反射。必须实例化类,然后才能通过反射调用所需的方法。您还可以将newInstance
强制转换为所需的类,然后直接调用方法。当然,在编译之前,你必须提前了解你的类李>UPD:
你的问题在这里`Class classType=Class。forName(f[i].getName();'
字段名不是它的类
你必须使用这个:
Class<?> classType = Class.forName(f[i].getType().getName());
此外,如果您想使用反射,您必须在
Target
类中将get_is()
方法声明为public请查看下面的工作代码,了解cast和reflection选项。(get_是目标类中的公共方法)