从 Java 中的字符串创建新对象 [英] Create new object from a string in Java

查看:36
本文介绍了从 Java 中的字符串创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 Java 中的 String 变量创建一个新类?

Is there a way to create a new class from a String variable in Java?

String className = "Class1";
//pseudocode follows
Object xyz = new className(param1, param2);

另外,如果可能的话,结果对象必须是 Object 类型吗?

Also, if possible does the resulting object have to be of type Object?

可能有更好的方法,但我希望能够从 XML 文件中检索值,然后实例化以这些字符串命名的类.这些类中的每一个都实现相同的接口并派生自相同的父类,因此我可以调用该类中的特定方法.

There may be a better way, but I want to be able to retrieve values from an XML file, then instantiate the classes named after those strings. Each of these classes implement the same interface and are derived from the same parent class, so I would then be able to call a particular method in that class.

推荐答案

这就是你想要做的:

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 文档

这篇关于从 Java 中的字符串创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆