简体   繁体   English

从Java中的类名实例化类

[英]instantiate class from class name in java

I try to instantiate class from a class name but I fail, my code is in Processing / Java Library. 我尝试从类名实例化类,但失败了,我的代码在Processing / Java Library中。 My first state it's find a good class, I manage that but after I find no possibility to instantiate from the class name. 我的第一个状态是找到一个好的类,我设法做到这一点,但是在我找不到从类名实例化的可能性之后。 I need to do that because all my methods is used everywhere in my code and I need to find information from those in a single place. 我之所以需要这样做,是因为我的所有方法都在代码中无处不在,而且我需要从一个地方查找这些信息。 I hope my purpose is clear... 我希望我的目的很明确...

I make this code but it's a fail, when I pass the name by method forName() the console return Unhandled exception type ClassNotFoundException 我编写了这段代码,但是失败了,当我通过方法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 object (you get it by calling Class.forName ) does not have a method get_is() . java.lang.Class对象(可通过调用Class.forName获取)没有方法get_is() You have to use reflection to call a method. 您必须使用反射来调用方法。

but... 但...

  1. As long as your get_is() is non-static you cannot call it from class even through reflection. 只要您的get_is()是非静态的,就不能通过反射从类中调用它。 You have to have instantiate your class and then you will be able to call needed method through reflection. 您必须实例化您的类,然后才能通过反射调用所需的方法。 You also can cast that newInstance to the desired class and then call method directly. 您还可以将该newInstance转换为所需的类,然后直接调用方法。 Of course, for that you have to know your class ahead before compile. 当然,为此,您必须在编译之前先了解您的课程。

UPD: UPD:

Your problem is in here `Class classType = Class.forName(f[i].getName());' 您的问题在这里`Class classType = Class.forName(f [i] .getName());'

Field name is not its class!. 字段名称不是其类!

you have to use this: Class<?> classType = Class.forName(f[i].getType().getName()); 您必须使用以下代码: Class<?> classType = Class.forName(f[i].getType().getName());

in addition if you'd like to use reflection you have to declare get_is() method as public in your Target class 另外,如果您想使用反射,则必须在Targetget_is()方法声明为public

Please look at working code below for both options cast and reflection. 请查看下面的工作代码,了解选项转换和反射。 (get_is method is public in Target class) (get_is方法在Target类中是公共的)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM