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

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

问题描述

可能的重复:
从 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.

我想知道怎么做...

推荐答案

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

"Using java.lang.reflect" will answer all your questions. First fetch the Class object using Class.forName(), and then:

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

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);

Class 上有一个 newInstance() 方法,它似乎可以满足您的需求.不要使用它.它将已检查的异常默默地转换为未检查的异常.

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.

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

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如何从字符串实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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