gpt4 book ai didi

Java如何从字符串实例化一个类

转载 作者:IT老高 更新时间:2023-10-28 21:02:43 25 4
gpt4 key购买 nike

Possible Duplicate:
Create new class from a Variable in Java

我有一个字符串

String className = "DummyClass"

现在我想创建一个类名为 className 的类对象,类似于

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

我想知道怎么做...

最佳答案

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

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() 方法,它似乎可以满足您的要求。 不要使用它。它以静默方式将已检查的异常转换为未检查的异常。

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如何从字符串实例化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7495785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com