Development Tip

문자열 매개 변수를 허용하는 생성자로 클래스 객체를 인스턴스화 하시겠습니까?

yourdevel 2020. 10. 29. 20:07
반응형

문자열 매개 변수를 허용하는 생성자로 클래스 객체를 인스턴스화 하시겠습니까?


Class단일 String인수 를 허용하는 생성자를 사용하여 개체에서 개체를 인스턴스화하고 싶습니다 .

내가 원하는 것에 접근하는 코드는 다음과 같습니다.

Object object = null;
Class classDefinition = Class.forName("javax.swing.JLabel");
object = classDefinition.newInstance();

그러나 JLabel텍스트없이 개체를 인스턴스화합니다 . JLabel문자열을 초기 텍스트로 받아들이 생성자 를 사용하고 싶습니다 . Class객체 에서 특정 생성자를 선택하는 방법이 있습니까?


Class.newInstance인수가없는 생성자 (매개 변수를 사용하지 않는 생성자)를 호출합니다. 다른 생성자를 호출하려면 리플렉션 패키지 ( java.lang.reflect) 를 사용해야합니다 .

다음 Constructor과 같은 인스턴스를 가져옵니다.

Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);

에 대한 호출 getConstructor은 단일 String매개 변수를 사용 하는 생성자를 원함 지정합니다 . 이제 인스턴스를 생성합니다.

Object o = cons.newInstance("JLabel");

그리고 당신은 끝났습니다.

추신 : 반사를 최후의 수단으로 사용하십시오!


다음이 효과가 있습니다. 이 시도,

Class[] type = { String.class };
Class classDefinition = Class.forName("javax.swing.JLabel"); 
Constructor cons = classDefinition .getConstructor(type);
Object[] obj = { "JLabel"};
return cons.newInstance(obj);

Class.forName("className").newInstance() 항상 인수 기본 생성자를 호출하지 않습니다.

인수가없는 생성자 대신 매개 변수화 된 생성자를 호출하려면

  1. 당신은 가야 Constructor의 종류를 전달하여 매개 변수 유형에 Class[]대한 getDeclaredConstructor방법Class
  2. 메서드 Object[]대한 값을 전달하여 생성자 인스턴스를 만들어야합니다.
    newInstanceConstructor

예제 코드 :

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

클래스가 생성자와 메서드를 호출하기 위해 객체를 생성 할 필요가없는 경우도 있습니다. 직접 객체를 생성하지 않고 클래스의 메서드를 호출 할 수 있습니다. 매개 변수로 생성자를 호출하는 것은 매우 쉽습니다.

import java.lang.reflect.*;
import java.util.*;

class RunDemo
{
    public RunDemo(String s)
    {
        System.out.println("Hello, I'm a constructor. Welcome, "+s);
    }  
    static void show()
    {
        System.out.println("Hello.");
    }
}
class Democlass
{
    public static void main(String args[])throws Exception
    {
        Class.forName("RunDemo");
        Constructor c = RunDemo.class.getConstructor(String.class);  
        RunDemo d = (RunDemo)c.newInstance("User");
        d.show();
    }
}

the output will be:

Hello, I'm a constructor. Welcome, User

Hello.

Class.forName("RunDemo"); will load the RunDemo Class.

Constructor c=RunDemo.class.getConstructor(String.class); getConstructor() method of Constructor class will return the constructor which having String as Argument and its reference is stored in object 'c' of Constructor class.

RunDemo d=(RunDemo)c.newInstance("User"); the method newInstance() of Constructor class will instantiate the RundDemo class and return the Generic version of object and it is converted into RunDemo type by using Type casting.

The object 'd' of RunDemo holds the reference returned by the newInstance() method.

참고URL : https://stackoverflow.com/questions/3574065/instantiate-a-class-object-with-constructor-that-accepts-a-string-parameter

반응형