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);
편집: 코멘트에 의하면, 일부의 유저에게는, 포인트 클래스나 메서드명만으로는 불충분한 것 같습니다.상세한 것에 대하여는, 컨스트럭터를 취득해 기동하기 위한 메뉴얼을 참조해 주세요.
다음과 같은 생성자가 있다고 가정합니다.
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(...)를 사용하여 다른 컨스트럭터를 가져올 수 있습니다.
파라미터화된 컨스트럭터를 호출하려면 다음 절차를 따릅니다.
- 얻다
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
클래스 메서드일련의 클래스가 필요합니다.다음으로 테스트 및 동작 예를 제시하겠습니다.
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' 카테고리의 다른 글
vuex 저장소 데이터를 그래프에 전달할 수 없음 (0) | 2022.08.31 |
---|---|
Vue.js - 부모 <-> 슬롯 통신 (0) | 2022.08.31 |
C의 문자열에 문자 추가? (0) | 2022.08.31 |
vuej를 사용한 다른 모바일 및 데스크톱 레이아웃 (0) | 2022.08.31 |
C에 선행 0이 있는 'printf' (0) | 2022.08.31 |