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具有所有细节。

更多相关文章

  1. 请问java中调用一个静态方法()内传入一个对象是表示什么意思?
  2. Java记录 -88- 利用反射机制调用对象的私有方法和属性
  3. Java开发水吧点饮品系统(顶层父类对象做接口参数)
  4. 如何知道Object是否为String类型对象?
  5. java入门第三篇-面向对象;
  6. 如何将树路径转换为json对象
  7. OOP面向对象编程(一)-------方法的重载
  8. Java学习(三)面向对象之多态
  9. 黑马程序员——Java学习笔记 String类和基本数据类型对象包装类

随机推荐

  1. Android版本与Linux内核版本的关系
  2. Android中的布局
  3. Monkey测试简介
  4. android binder机制之--(我是Service Mana
  5. 下载频道2013年超人气精华资源汇总---全
  6. Android 应用开发笔记 - 图片视图(ImageVi
  7. 最易用的 Android HTTP library
  8. 如何向Android模拟器打电话发短信
  9. EditText 报出 “This text field does n
  10. 【android 其他】转载:Android 简史