If you know that the class has a no-arg constructor you can just call c.newInstance()
. Otherwise you need to call the overloaded version of newInstance()
which accepts arguments.
New instance of an arbitrary class [duplicate]
-
18-07-2023 - |
Domanda
In Java, how can I create a new instance of a class, where the class is not selected until the code is run?
List<Class> classes = new ArrayList<>();
classes.add(String.class);
classes.add(ArrayList.class);
classes.add(Integer.class);
classes.add(Random.class);
Random r = new Random();
Class c = classes.get(r.nextInt(classes.size()));
Object o = // new instance of "c"
Soluzione
Altri suggerimenti
Try in this way but not a good way.
Class<?> clazz = String.class;
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { "abc" });
System.out.println(object); // print abc
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow