且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 Java 中的字符串创建新对象

更新时间:2021-09-20 18:54:56

这就是你想要做的:

String className = "Class1";
Object xyz = Class.forName(className).newInstance();

请注意,newInstance 方法不允许使用参数化构造函数.(请参阅 Class.newInstance 文档)

Note that the newInstance method does not allow a parametrized constructor to be used. (See Class.newInstance documentation)

如果您确实需要使用参数化构造函数,这就是您需要做的:

If you do need to use a parametrized constructor, this is what you need to do:

import java.lang.reflect.*;

Param1Type param1;
Param2Type param2;
String className = "Class1";
Class cl = Class.forName(className);
Constructor con = cl.getConstructor(Param1Type.class, Param2Type.class);
Object xyz = con.newInstance(param1, param2);

参见 Constructor.newInstance 文档