使用类名创建实例并调用构造函数 [英] Creating an instance using the class name and calling constructor
问题描述
有没有办法在给定类名(动态)的情况下创建特定类的实例,并将参数传递给它的构造函数。
类似于:
Object object = createInstance(mypackage.MyClass,MyAttributeValue);
其中MyAttributeValue
是一个参数 MyClass的构造函数
。
是的,类似于:
Class<?> clazz = Class.forName(className);
构造函数<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object [] {ctorArgument});
当然,这只适用于单个字符串参数,但你可以很容易地修改它。 / p>
请注意,类名必须是完全限定的类名,即包括名称空间。对于嵌套类,您需要使用一美元(就像编译器使用的那样)。例如:
package foo;
公共类外部
{
公共静态类嵌套{}
}
要获得 Class
对象,你需要 Class.forName(foo.Outer $嵌套)
。
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
.
Yes, something like:
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });
That will only work for a single string parameter of course, but you can modify it pretty easily.
Note that the class name has to be a fully-qualified one, i.e. including the namespace. For nested classes, you need to use a dollar (as that's what the compiler uses). For example:
package foo;
public class Outer
{
public static class Nested {}
}
To obtain the Class
object for that, you'd need Class.forName("foo.Outer$Nested")
.
这篇关于使用类名创建实例并调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!