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

查看:253
本文介绍了从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天全站免登陆