Java 如何将类转换为实例对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9714093/
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 convert Class to Instance Object
提问by Poringe
take a look at my code....
看看我的代码....
Class<?> c = Class.forName("PerformanceInvokeService");
Method m = c.getDeclaredMethod("monthlyTestCal", new Class[] {
String.class, Date.class });
Object ret = m.invoke("PerformanceInvokeService", new Object[] {
"some string", new Date() });
System.out.println(ret);
i execute this and its thrown an exception
我执行这个并抛出异常
java.lang.IllegalArgumentException: object is not an instance of declaring class
i think, because i don't create an instance of c (likes...new PerformanceInvokeService()) and i don't know how to create it
我想,因为我没有创建 c 的实例(喜欢...new PerformanceInvokeService())而且我不知道如何创建它
somebody help?
有人帮忙吗?
sorry for my english...
对不起我的英语不好...
thanks
谢谢
采纳答案by Ted Hopp
If PerformanceInvokeService
has an accessible default constructor, you can create a new instance using:
如果PerformanceInvokeService
有一个可访问的默认构造函数,您可以使用以下方法创建一个新实例:
Object instance = c.newInstance();
You can then pass that to the method invocation:
然后,您可以将其传递给方法调用:
Object ret = m.invoke(instance, new Object[] { "some string", new Date() });
If there is no accessible default constructor, then you'll have to find a constructor that you can use by using reflection.
如果没有可访问的默认构造函数,那么您必须找到一个可以通过反射使用的构造函数。
回答by Wyzard
Class
has a newInstance()
method that you can call to create an instance of the class using its default constructor. Or, you can call getConstructor()
or getConstructors()
to find a constructor that takes the right kind of arguments, and then call newInstance()
on the Constructor
object, passing the construction arguments.
Class
有一个newInstance()
方法,您可以调用该方法使用其默认构造函数创建类的实例。或者,您可以调用getConstructor()
或getConstructors()
找到一个接受正确类型参数的构造函数,然后调用newInstance()
该Constructor
对象,传递构造参数。
回答by Jochen
You need to add
你需要添加
Object myInstance = c.newInstance();
This will call the default constructor and create a new object. Then you can use this as the first argument in
这将调用默认构造函数并创建一个新对象。然后你可以使用它作为第一个参数
m.invoke()