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?
8 回答
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
or
obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
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 constuctor and invoking it.
假设您有以下构造函数
class MyClass {
public MyClass(Long l, String s, int i) {
}
}
你需要表明你打算像这样使用这个构造函数:
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);
不要使用Class.newInstance()
;看到这个线程:为什么 Class.newInstance() 是邪恶的?
就像其他答案说的那样,Constructor.newInstance()
改用。
You can get other constructors with getConstructor(...).
按照以下步骤调用参数化构造函数。
Constructor
通过将类型传入Class[]
forgetDeclaredConstructor
方法获取参数类型Class
Object[]
通过在for
newInstance
方法中传递值来创建构造函数实例Constructor
示例代码:
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"});
}
}
输出:
java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow
我认为这正是你想要的 http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html
虽然它似乎是一个死线程,但有人可能会发现它很有用
你可以使用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;
}
}