programing

Class.newInstance()를 컨스트럭터 인수와 함께 사용할 수 있습니까?

bestcode 2022. 8. 31. 22:44
반응형

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(...)를 사용하여 다른 컨스트럭터를 가져올 수 있습니다.

파라미터화된 컨스트럭터를 호출하려면 다음 절차를 따릅니다.

  1. 얻다Constructor매개 변수 유형을 사용하여 전달Class[]위해서getDeclaredConstructor의 방법Class
  2. 다음 위치에서 값을 전달하여 생성자 인스턴스 생성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

반응형