简体   繁体   中英

creating classes based on Object.class

I want to define a list of classes and instantiate them later. I have a list like this

List<Class> classList = new ArrayList<>();
classList.add(ClassA.class);
classList.add(ClassB.class);

I want to read from this list and create the classes. I don't know witch classes I have to create since clients of my library will define this list. All i know is all of this classes extend from the same class and have one object as constructor argument.
Any idea how should i achieve this?

If constructors of all your classes in question accept a single parameter, and the type of that parameter is the same (let's say it's String ), you could instantiate such a class with the following:

Object instance = clazz.getConstructor(String.class).newInstance("string value you pass to the constructor");

Also, if all your classes extend class Super , it's better to write Class<? extends Super> Class<? extends Super> instead of raw Class . Then you could write

Super instance = clazz.getConstructor(String.class).newInstance("string value you pass to the constructor");

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