如何从Java类中的类名获取类对象 [英] How to get a Class Object from the Class Name in Java

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

问题描述

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

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

我浏览过网页,但我发现的大部分的东西是关于 ClassLoader ,我认为不适合我的情况。我不想初始化一个类,但只能得到一个类对象以备将来使用。

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.

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

Regarding the first answers to this:

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

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 false to the second argument, but would the third have to be null or what?

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

return MyClass.class

事实上,我想做的是替换与 Class 对象相关联的String ID数组, ID从中自动获取类对象,以摆脱一些手动工作:)

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

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

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

推荐答案

您可以使用:

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

稍后实例化一个对象:

Object obj = c.newInstance();

编辑:这只是最简单的用例。如注释中所示,您将需要考虑由初始化过程抛出的构造函数参数和异常。 JavaDocs newInstance 具有所有详细信息。

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 newInstance has all the details.

这篇关于如何从Java类中的类名获取类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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