Java 我可以将 Class.newInstance() 与构造函数参数一起使用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/234600/
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
Can I use Class.newInstance() with constructor arguments?
提问by
I would like to use Class.newInstance()
but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?
我想使用Class.newInstance()
但我正在实例化的类没有空构造函数。因此我需要能够传入构造函数参数。有没有办法做到这一点?
回答by iny
You can get other constructors with getConstructor(...).
您可以使用getConstructor(...)获得其他构造函数。
回答by Marko
myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);
Edit: according to the comments seems like pointing class and method names is not enough for some users. For more info take a look at the documentation for getting constuctorand invoking it.
回答by jsight
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
or
或者
obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
回答by Chris Jester-Young
Do not use Class.newInstance()
; see this thread: Why is Class.newInstance() evil?
不要使用Class.newInstance()
; 看到这个线程:为什么 Class.newInstance() 是邪恶的?
Like other answers say, use Constructor.newInstance()
instead.
就像其他答案所说的那样,请Constructor.newInstance()
改用。
回答by Lajos Arpad
You can use the getDeclaredConstructor
method of Class. It expects an array of classes. Here is a tested and working example:
您可以使用getDeclaredConstructor
Class的方法。它需要一个类数组。这是一个经过测试且有效的示例:
public static JFrame createJFrame(Class c, String name, Component parentComponent)
{
try
{
JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance("name");
if (parentComponent != null)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else
{
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
frame.setLocationRelativeTo(parentComponent);
frame.pack();
frame.setVisible(true);
}
catch (InstantiationException instantiationException)
{
ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());
}
catch(NoSuchMethodException noSuchMethodException)
{
//ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, "NamedConstructor");
ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), "(Constructor or a JFrame method)");
}
catch (IllegalAccessException illegalAccessException)
{
ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));
}
catch (InvocationTargetException invocationTargetException)
{
ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));
}
finally
{
return null;
}
}
回答by Spyros Doulgeridis
I think this is exactly what you want http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html
我认为这正是你想要的 http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html
Although it seems a dead thread, someone might find it useful
虽然它似乎是一个死线程,但有人可能会发现它很有用
回答by Martin Konecny
Assuming you have the following constructor
假设您有以下构造函数
class MyClass {
public MyClass(Long l, String s, int i) {
}
}
You will need to show you intend to use this constructor like so:
你需要表明你打算像这样使用这个构造函数:
Class classToLoad = MyClass.class;
Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int
Long l = new Long(88);
String s = "text";
int i = 5;
classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);
回答by Ravindra babu
Follow below steps to call parameterized consturctor.
按照以下步骤调用参数化构造函数。
- Get
Constructor
with parameter types by passing types inClass[]
forgetDeclaredConstructor
method ofClass
- Create constructor instance by passing values in
Object[]
fornewInstance
method ofConstructor
Constructor
通过在Class[]
forgetDeclaredConstructor
方法中传递类型来获取参数类型Class
- 通过在
Object[]
fornewInstance
方法中传递值来创建构造函数实例Constructor
Example code:
示例代码:
import java.lang.reflect.*;
class NewInstanceWithReflection{
public NewInstanceWithReflection(){
System.out.println("Default constructor");
}
public NewInstanceWithReflection( String a){
System.out.println("Constructor :String => "+a);
}
public static void main(String args[]) throws Exception {
NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});
NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});
}
}
output:
输出:
java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow