我尝试从类名实例化类,但失败了,我的代码在Processing / Java Library中。我的第一个状态是找到一个好的类,我做到了,但在我发现没有可能从类名实例化之后。我需要这样做,因为我的所有方法都在代码中的任何地方使用,并且我需要在一个地方从这些方法中查找信息。我希望我的目的是明确的。
我写了这段代码,但它失败了,当我通过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() {}
}
发布于 2018-06-13 06:53:03
java.lang.Class
对象(通过调用Class.forName
获得它)没有get_is()
方法。您必须使用反射来调用方法。但是..。
get_is()
是非静态的,你就不能从类中调用它,即使是通过反射。您必须实例化您的类,然后才能通过反射调用所需的方法。您还可以将该newInstance
转换为所需的类,然后直接调用方法。当然,要做到这一点,你必须在编译之前提前了解你的类。更新:
你的问题在这里` `Class = Class.forName(fi.getName());‘
字段名不是它的类!.
你必须使用这个:Class<?> classType = Class.forName(f[i].getType().getName());
此外,如果您希望使用反射,则必须在Target
类中将get_is()
方法声明为公共方法
请查看下面的选项强制转换和反射的工作代码。(get_is方法在目标类中是公共的)
for(int i = 0 ; i < f.length ; i++) {
// class is field type not name!
Class<?> classType = Class.forName(f[i].getType().getName());
// check is it Target class type
if (f[i].getType().equals(Target.class)) {
System.out.println("it is Target class field!");
// option 1: cast
Target targetFieldValue = (Target)f[i].get(this);
System.out.println("opt1-cast -> field:" + f[i].getName() + " result: " + targetFieldValue.get_is());
//option 2: reflection
Object rawValue = f[i].get(this);
Method getIsMtd = f[i].getType().getMethod("get_is", (Class<?>[])null);
if (null != getIsMtd)
{
// invoke it
System.out.println("opt2 -> reflection result: " + getIsMtd.invoke(rawValue, (Object[])null));
}
}
}
https://stackoverflow.com/questions/50826844
复制相似问题