Java如何从string实例化一个类 [英] Java how to instantiate a class from string

查看:87
本文介绍了Java如何从string实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

从Java中的变量创建新类

我有一个字符串

String className = "DummyClass"

现在我要创建一个类对象,其中类名是 className 这就像

Now I want to create a class object where the class name is className That is something like

Object className = new className() // I know it's not possible.

我想知道怎么做...

I want to know how to do this...

推荐答案

使用 java.lang.reflect 将回答您的所有问题。首先使用 Class.forName()获取 Class 对象,然后:


如果我想实例化一个用 forName()检索的类,我必须首先要求它 java.lang.reflect.Constructor 表示我想要的构造函数的对象,然后要求构造函数创建一个新对象。 中的方法 getConstructor(Class [] parameterTypes)将检索构造函数;然后我可以通过调用它的方法 newInstance(Object [] parameters)

If I want to instantiate a class that I retrieved with forName(), I have to first ask it for a java.lang.reflect.Constructor object representing the constructor I want, and then ask that Constructor to make a new object. The method getConstructor(Class[] parameterTypes) in Class will retrieve a Constructor; I can then use that Constructor by calling its method newInstance(Object[] parameters):

Class myClass = Class.forName("MyClass");

Class[] types = {Double.TYPE, this.getClass()};
Constructor constructor = myClass.getConstructor(types);

Object[] parameters = {new Double(0), this};
Object instanceOfMyClass = constructor.newInstance(parameters);


有一个 newInstance() Class 上的方法似乎可以做你想要的。 不要使用。它会将已检查的异常静默转换为未经检查的异常。

There is a newInstance() method on Class that might seem to do what you want. Do not use it. It silently converts checked exceptions to unchecked exceptions.


请注意,此方法会传播由Nullary构造函数抛出的任何异常,包括已检查的异常。使用此方法可以有效地绕过编译时异常检查,否则将由编译器执行。 Constructor.newInstance 方法通过将构造函数抛出的任何异常包装在(已检查的) InvocationTargetException 中来避免此问题。 / p>

Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) InvocationTargetException.

这篇关于Java如何从string实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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