如何从 Java 中的类名获取类对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1438420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:16:05  来源:igfitidea点击:

How to get a Class Object from the Class Name in Java

javareflectionclass

提问by alkar

I know the class name, say "MyClass"and want to retrieve the Classobject, ie. MyClass.classfor future references. Is there a way to do that?

我知道类名,说“MyClass”并想要检索Class对象,即。MyClass.class以供将来参考。有没有办法做到这一点?

I've looked through the web but most of the things I found related to it were about the ClassLoader, which I presume are not suitable for my case. I do not want to initialize a class, but only get a class object for future uses.

我浏览了网络,但我发现与之相关的大部分内容都是关于 的ClassLoader,我认为这不适合我的情况。我不想初始化一个类,而只想获取一个类对象以备将来使用。

EDIT: Regarding the first answers to this:

编辑:关于这个的第一个答案:

I've already checked the forName()method but I thought that is supposed to also initialize the class. Now I can call it with the full arguments and pass falseto the second argument, but would the third have to be nullor what?

我已经检查了该forName()方法,但我认为这也应该初始化该类。现在我可以用完整的参数调用它并传递false给第二个参数,但是第三个必须是null还是什么?

Would

Class.forName("MyClass", false, null);

return MyClass.class?

返回MyClass.class

In fact, what I want to do, is replace an array of String IDs associated with Classobjects, with an array of IDs from which the class objects are fetched automatically, to get rid of some manual work :)

实际上,我想要做的是将与Class对象关联的字符串 ID 数组替换为自动从中获取类对象的 ID 数组,以摆脱一些手动工作:)

Thanks for the quick answers and sorry for not mentioning this before.

感谢您的快速回答,很抱歉之前没有提到这一点。

采纳答案by Tony the Pony

You can use:

您可以使用:

Class c = Class.forName("com.package.MyClass");

And later instantiate an object:

然后实例化一个对象:

Object obj = c.newInstance();

EDIT: This is just the simplest use case. As indicated in the comments, you will need to consider constructor arguments and exceptions thrown by the initialization process. The JavaDocs for newInstancehas all the details.

编辑:这只是最简单的用例。如注释中所述,您将需要考虑初始化过程引发的构造函数参数和异常。该对JavaDoc中newInstance有所有的细节。

回答by Joachim Sauer

Class.forName("MyClass")

Read the JavaDocfor details

阅读JavaDoc了解详细信息

回答by Thomas Owens

It sounds like you might be able to use the Classclass's static forNamemethod.

听起来您或许可以使用Class该类的静态forName方法

回答by Droo

It's also worth noting that the above suggestions are correct, but will only work for default (parameterless) constructors. You could also do something like:

还值得注意的是,上述建议是正确的,但仅适用于默认(无参数)构造函数。您还可以执行以下操作:

    public Object newInstance(String className, Object...args) throws Exception {
        Class<?> clazz = Class.forName(className);
        if(args == null || args.length == 0) {
            return clazz.newInstance();
        }

        List<Class<?>> argTypes = new ArrayList<Class<?>>();
        for(Object object : args) {
            argTypes.add(object.getClass());
        }
        Constructor<?> explicitConstructor = clazz.getConstructor(argTypes.toArray(new Class[argTypes.size()]));
        return explicitConstructor.newInstance(args);
    }

回答by William H. Hooper

If you don't want to specify the full package name, call:

如果您不想指定完整的包名称,请调用:

Class.forName("MyClass", true, this.getClass().getClassLoader());

This syntax allows you to reorganize the project, or copy this code into another project, as long as you move MyClassalong with it. Thanks to Joachimfor reminding me to read the docs!

此语法允许您重新组织项目,或将此代码复制到另一个项目中,只要您将MyClass与它一起移动即可。感谢Joachim提醒我阅读文档!