생성자 인수와 함께 Class.newInstance ()를 사용할 수 있습니까?
사용하고 Class.newInstance()
싶지만 인스턴스화하는 클래스에 null 생성자가 없습니다. 따라서 생성자 인수를 전달할 수 있어야합니다. 이것을 할 수있는 방법이 있습니까?
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
또는
obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);
편집 : 의견에 따르면 클래스를 가리키는 것처럼 보이고 일부 사용자에게는 메서드 이름이 충분하지 않습니다. 더 많은 정보 설명서를 살펴 걸릴 constructor에 점점 하고 그것을 호출을 .
다음 생성자가 있다고 가정합니다.
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()
대신 사용하십시오.
getConstructor (...)로 다른 생성자를 얻을 수 있습니다 .
파라미터 화 된 consturctor를 호출하려면 아래 단계를 따르십시오.
- 가져 오기
Constructor
에 유형을 전달하여 매개 변수 유형에Class[]
대한getDeclaredConstructor
방법Class
- 값을 전달하여 생성자 인스턴스를 만들기
Object[]
위한
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
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;
}
}
나는 이것이 당신이 원하는 것 같아요 http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html
스레드가 죽은 것처럼 보이지만 누군가 유용 할 수 있습니다.
참고 URL : https://stackoverflow.com/questions/234600/can-i-use-class-newinstance-with-constructor-arguments
'Programing' 카테고리의 다른 글
WebView의 Android 호출 JavaScript 함수 (0) | 2020.04.17 |
---|---|
Oracle 데이터베이스에 부울 유형이 있습니까? (0) | 2020.04.17 |
iOS에서 base64 인코딩을 어떻게 수행합니까? (0) | 2020.04.17 |
Visual Studio 2012 Ultimate RC에서 Intellisense 및 코드 제안이 작동하지 않음 (0) | 2020.04.17 |
innerText와 innerHTML의 차이점 (0) | 2020.04.17 |