ProgramingTip

Java의 공유에서 새 개체 만들기

bestdevel 2020. 11. 17. 20:41
반응형

Java의 공유에서 새 개체 만들기


Java의 문자열 변수에서 새 클래스를 만드는 방법이 있습니까?

String className = "Class1";
//pseudocode follows
Object xyz = new className(param1, param2);

또한 가능합니다.

더 나은 방법이있을 수 있습니다. XML 파일에서 값을 검색 한 다음 해당하는 클래스를 따라 명명 된 클래스를 인스턴스화 할 수 있기를 원합니다. 각 클래스는 동일한 인터페이스를 구현하고 그 클래스에서 파생 된 클래스에서 호출 할 수 있습니다.


이것은 당신이 원하는 것입니다.

String className = "Class1";
Object xyz = Class.forName(className).newInstance();

newInstance 메서드는 매개 변수화 된 생성 사용할 수 없습니다. ( Class.newInstance 문서 참조 )

사용하는 경우에는 다음을 수행해야합니다.

import java.lang.reflect.*;

Param1Type param1;
Param2Type param2;
String className = "Class1";
Class cl = Class.forName(className);
Constructor con = cl.getConstructor(Param1Type.class, Param2Type.class);
Object xyz = con.newInstance(param1, param2);

Constructor.newInstance 문서 참조


예, 리플렉션을 사용하고 Class.forName (이름)을 사용하여 생성하여 생성 할 호출하여 String 이름이 지정된 클래스 경로에 클래스를로드 할 수 있습니다. 예를 들어 보겠습니다.

수업이 많이 생각하십시오.

com.crossedstreams.thingy.Foo

서명이 있습니다.

Foo(String a, String b);

이 두 가지 사실을 기반으로 다음과 같이 클래스를 인스턴스화합니다.

// Load the Class. Must use fully qualified name here!
Class clazz = Class.forName("com.crossedstreams.thingy.Foo");

// I need an array as follows to describe the signature
Class[] parameters = new Class[] {String.class, String.class};

// Now I can get a reference to the right constructor
Constructor constructor = clazz.getConstructor(parameters);

// And I can use that Constructor to instantiate the class
Object o = constructor.newInstance(new Object[] {"one", "two"});

// To prove it's really there...
System.out.println(o);

다수 :

com.crossedstreams.thingy.Foo@20cf2c80

이것에 더 많은 리소스가 있고 컴파일러가 자세히 확인하고 알고 있어야한다는 사실을 알고 있습니다. 클래스 이름이나 기타 철 잘못 입력하면 작동에 실패합니다. . 또한 여러 가지 유형의 예외가 있습니다. 그래도 매우 강력한 기술입니다.


작동합니다.

import java.lang.reflect.*;

FirstArgType arg1;
SecondArgType arg2;
Class cl = Class.forName("TheClassName");
Constructor con = cl.getConstructor(FirstArgType.class, SecondArgType.class);
Object obj = con.newInstance(arg1, arg2);

장착 할 수 있습니다.


이것은 JDK7에서 나를 위해 조금 더 깨끗하게 작동했지만 위의 답변은 초보자 관점에서 필요했던 것보다 조금 더 어렵게 만들었습니다. ( 'className'을 메서드 매개 변수로 전달 된 문자열 변수로 선언했다고 가정하거나 이 코드를 사용하는 방법의 앞부분) :

Class<?> panel = Class.forName( className );
JPanel newScreen = (JPanel) panel.newInstance();

이 시점에서 동적으로 이름이 지정된 클래스의 속성 / 메서드를 사용할 수있을 것으로 예상하는대로 정확하게 사용할 수 있습니다.

JFrame frame = new JFrame(); // <<< Just so no-one gets lost here
frame.getContentPane().removeAll();
frame.getContentPane().add( newScreen );
frame.validate();
frame.repaint();

위의 다른 답변의 예제는 새로운 'Object'유형 객체를 프레임에 .add ()하려고 할 때 오류가 발생했습니다. 여기에 표시된 기술은 위의 두 줄의 코드만으로 사용 가능한 객체를 제공했습니다.

그 이유가 정확히 확실하지 않습니다. 저는 Java 초보자입니다.


다른 것:

import java.lang.reflect.Constructor;

public class Test {

 public Test(String name) {
    this.name = name;
 }

 public String getName() {
    return name;
 }

 public String toString() {
    return this.name;
 }

 private String name;

 public static void main(String[] args) throws Exception {
    String className = "Test";
    Class clazz = Class.forName(className);
    Constructor tc = clazz.getConstructor(String.class);
    Object t = tc.newInstance("John");
    System.out.println(t);
 }
}

class사용 String개체의 인스턴스를 가져 오는 샘플 프로그램 .

public class GetStudentObjectFromString
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String className = "Student"; //Passed the Class Name in String Object.

         //A Object of Student will made by Invoking its Default Constructor.
        Object o = Class.forName(className).newInstance(); 
        if(o instanceof Student) // Verify Your Instance that Is it Student Type or not?
        System.out.println("Hurrey You Got The Instance of " + className);
    }
}
class Student{
    public Student(){
        System.out.println("Constructor Invoked");
    }

}

출력 :-

 Constructor Invoked
 Hurrey You Got The Instance of Student

참고 URL : https://stackoverflow.com/questions/1268817/create-new-object-from-a-string-in-java

반응형