如何从Java中的类名获取类对象
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?
我知道类名,说“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 false
to the second argument, but would the third have to be null
or 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 Class
objects, with an array of IDs from which the class objects are fetched automatically, to get rid of some manual work :)
事实上,我想要做的是替换与Class对象关联的String ID数组,以及从中自动获取类对象的ID数组,以摆脱一些手动工作:)
Thanks for the quick answers and sorry for not mentioning this before.
感谢您的快速回答,并且抱歉之前没有提及此问题。
4 个解决方案
#1
45
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 newInstance
has all the details.
编辑:这只是最简单的用例。如注释中所示,您将需要考虑初始化过程抛出的构造函数参数和异常。 newInstance的JavaDocs具有所有细节。
更多相关文章
- 请问java中调用一个静态方法()内传入一个对象是表示什么意思?
- Java记录 -88- 利用反射机制调用对象的私有方法和属性
- Java开发水吧点饮品系统(顶层父类对象做接口参数)
- 如何知道Object是否为String类型对象?
- java入门第三篇-面向对象;
- 如何将树路径转换为json对象
- OOP面向对象编程(一)-------方法的重载
- Java学习(三)面向对象之多态
- 黑马程序员——Java学习笔记 String类和基本数据类型对象包装类