有没有办法根据类名(动态)创建特定类的实例并将参数传递给其构造函数.
Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor.
类似于:
Object object = createInstance("mypackage.MyClass","MyAttributeValue");其中 "MyAttributeValue" 是 MyClass 的构造函数的参数.
Where "MyAttributeValue" is an argument to the constructor of MyClass.
推荐答案是的,例如:
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 {} }要为此获得 Class 对象,您需要 Class.forName("foo.Outer$Nested").
To obtain the Class object for that, you'd need Class.forName("foo.Outer$Nested").
更多推荐
使用类名和调用构造函数创建实例
发布评论