简体   繁体   English

使用参数化构造函数实例化一组给定的类

[英]Instantiating a given set of classes with parameterized constructors

Is it possible in Java to take a collection of classes with parameterized constructors and instantiate each one of them at run time? 在Java中,是否可以使用带有参数化构造函数的类的集合,并在运行时实例化每个实例? These classes have only one constructor that can take any number of primitive type arguments, though the number of arguments they take can vary for each class. 这些类只有一个可以接受任意数量的原始类型参数的构造函数,尽管它们所接受的参数数量对于每个类而言可能有所不同。 As an example, here are four classes that we want to instantiate at run time: 例如,以下是我们要在运行时实例化的四个类:

 public class One { public One(int a) { } }
 public class Two { public Two(char a, int b) { } }
 public class Three { public Three(float a, char b, int c) { } }
 public class Four { public Four(float a, char b, int c) { } }
Class oneC = Class.forName("One"); // use FQCN
Contructor constructor = oncC.getConstructors()[0]; // assuming that the class has only 1 constructor
Class<?>[] paramTypes = constructor.getParameterTypes();
// Iterate paramTypes, create each parameter value and then call constructor.newInstance(...)

Reference: 参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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