简体   繁体   中英

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. 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

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() . 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. 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. Of course, for that you have to know your class ahead before compile.

UPD:

Your problem is in here `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());

in addition if you'd like to use reflection you have to declare get_is() method as public in your Target class

Please look at working code below for both options cast and reflection. (get_is method is public in Target class)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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