有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从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) 个答案

  1. # 1 楼答案

    1. java.lang.Class对象(通过调用Class.forName获得)没有方法get_is()。必须使用反射来调用方法

    但是

    1. 只要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_是目标类中的公共方法)

          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));
             }   
         } 
       }