I created an ArrayList to store Classes. Then I would like to use the members in the ArrayList to create an instance. How can I instantiate?
import java.util.ArrayList;
class Machine{
public String toString(){
return "I am a machine";
}
}
class MyMachine extends Machine{
public String toString(){
return "This is a super Machine";
}
}
class MyClass<T> {
public static <T> void showString(T abc){
System.out.println(abc);
}
}
public class myfun {
public static void main(String[] args) {
ArrayList<Class> hahalist = new ArrayList<>();
hahalist.add(MyClass.class);
hahalist.add(Machine.class);
hahalist.add(MyClass.class);
// Machine abc = new Machine();
// I can't do this
// abc = hahalist.get(1);
// I can't do this either
// hahalist.get(1) abc = new hahalist.get(1)()
}
}
If you have a no args constructor on all you classes you can just use the Class.newInstance(), eg
try {
Object x = hahaList.get(0).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
(I haven't got my IDE open so haven't verified the exact syntax).
If you've got arguments to the constructor then its a bit more convoluted. You can read the full details here: https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
Instead of storing classes in the list, you could store references to the constructors:
List<Supplier<Object>> hahalist = new ArrayList<>();
hahalist.add(MyClass::new);
hahalist.add(Machine::new);
hahalist.add(MyMachine::new);
Object instance = hahalist.get(1).get(); // Calling constructor
Because MyClass
and Machine
have a closest common ancestor of Object
that is the return type of the Supplier
I'm using here.
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.