如何从 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
How to get a Class Object from the Class Name in Java
提问by alkar
I know the class name, say "MyClass"and want to retrieve the Class
object, 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 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
对象关联的字符串 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 newInstance
has all the details.
编辑:这只是最简单的用例。如注释中所述,您将需要考虑初始化过程引发的构造函数参数和异常。该对JavaDoc中newInstance
有所有的细节。
回答by Joachim Sauer
回答by Thomas Owens
It sounds like you might be able to use the Class
class's static forName
method.
回答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提醒我阅读文档!