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() {}
}