本文翻译自:Creating an instance using the class name and calling constructor
Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor. 有没有一种方法可以给定类名称(动态)来创建特定类的实例,并将参数传递给其构造函数。
Something like: 就像是:
Object object = createInstance("mypackage.MyClass","MyAttributeValue");
Where "MyAttributeValue"
is an argument to the constructor of MyClass
. 其中"MyAttributeValue"
是MyClass
的构造函数的参数。
#1楼
参考:https://stackoom.com/question/PZTb/使用类名称创建实例并调用构造函数
#2楼
If class has only one empty constructor (like Activity or Fragment etc, android classes): 如果class只有一个空的构造函数(例如Activity或Fragment等,android类):
Class<?