在 Java 中从类名实例化类



我尝试从类名实例化类,但我失败了,我的代码在处理/Java库中。 我的第一个状态是找到一个好的类,我管理它,但在我发现不可能从类名实例化之后。我需要这样做,因为我的所有方法在我的代码中随处使用,我需要从一个地方从这些方法中查找信息。 我希望我的目的很明确...

我制作了这段代码,但当我通过 Name(( 方法传递名称时,它失败了 控制台返回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()。您必须使用反射来调用方法。

但。。。

  1. 只要你的get_is()是非静态的,即使通过反射,你也无法从课堂上调用它。你必须实例化你的类,然后你才能通过反射调用所需的方法。还可以将该newInstance强制转换为所需的类,然后直接调用方法。当然,为此,您必须在编译之前提前了解您的类。

上级:

你的问题在这里'类类类型 = Class.forName(f[i].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));
}   
} 
}

最新更新