从Java中的Variable创建新类 [英] Create new class from a Variable in Java

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

问题描述

有没有办法从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 create the classes named after those strings. Each of classes all 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.

推荐答案

这就是你想要做的事情:

This is what you want to do:

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中的Variable创建新类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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