2014-01-17 4 views
2

나는 두 개의 인스턴스 필드를 포함하는 Creator라고 부르겠습니다. 이 필드는 부모 클래스 A에 속합니다. 생성자의 생성자에서 클래스 A의 자식을 전달한 다음 전달 된 형식에서 두 개체를 만들고 두 필드에 참조를 할당하려고합니다. 나는 어떻게 그런 것을 할 수 있습니까? 나는이 일반화를 만드는 방법을 모른다.오브젝트 유형을 전달하여 많은 오브젝트를 작성하는 방법은 무엇입니까?

편집 : 클래스 작성자 은 A 또는 A 자체의 하위 유형을 허용해야합니다. 그래서 다른 어떤 일반적인 유형. A는 인수가없는 생성자에게 그래서 이런

이없는, 여기 GeneralClassifier A는하고 인수가없는 생성자가 없습니다 :

public class TwoLevelClassifier <T> { 

    private GeneralClassifier firstCl, secondCl; 

    //The passed type shall *only* be a GeneralClassifier or a child of it 
    public TwoLevelClassifier(GeneralClassifier cl) { 
     firstCl = //create a new classifier that is of the type passed to the constructor 
     secondCl = //create a new classifier that is of the type passed to the constructor 
    } 

} 

잘 모르겠어요,하지만 어쩌면이 기능은 자바에서 제네릭이라고?

+1

리플렉션을 사용해야합니다. 이것을 참조하십시오 : http://stackoverflow.com/questions/10470263/create-new-object-using-reflection – Massimo

+1

제네릭을 사용하지 않는 이유는 무엇입니까? 'public class Creator {' – crush

+0

자식 유형의 인스턴스를 ctor의 매개 변수로 전달해야합니까? 당신은 그걸 가지고 아무 것도하지 않으므로, 나는 그럴 수 없다고 생각합니다. – crush

답변

7

당신이 사용하는 반사를 수행 할 수 있습니다

public class Creator<A> { 
    A a, b; 

    public Creator(Class<A> childrenType) throws IllegalAccessException, InstantiationException { 
     a = childrenType.newInstance(); 
     b = childrenType.newInstance(); 
    } 
} 

참고 :이 사용하는 클래스가없는 인수 생성자가 있다고 가정합니다.

편집 당신은 본래의 질문을 크게 편집했습니다.

public class Creator<A extends GeneralClassifier> { 

클래스 A가 아니 -이없는 요구를 들어 : 유형 AGeneralClassifier 또는 그 서브 클래스는, 형식 매개 변수에 제약 조건을 추가되어야하는 요구 사항에 대한

argument constructor : 그러면 사용하고자하는 생성자를 찾아서 적절한 인자로 호출해야합니다. 당신은 미리 호출해야하는 생성자를 알아야합니다. String을 사용하는 생성자를 호출한다고 가정합니다. 클래스 java.lang.Class

Constructor<A> constr = childrenType.getConstructor(String.class); 
a = constr.newInstance("Hello"); 
b = constr.newInstance("Bye"); 

참조 API 문서 및 패키지 java.lang.reflect : 그럼 이런 일이 될 것입니다.

당신은 너무

// <TYPE> is the generic type. 
public class Creator<TYPE> { 
    TYPE a = null, b = null; 

    public Creator(Class<TYPE> childrenType) { 
     try { 
      // newInstance is reflection. 
      a = childrenType.newInstance(); 
      b = childrenType.newInstance(); 
     } catch (InstantiationException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

처럼 반사와 제네릭 비슷한 일을 할 수 있거나, 당신이 (예를 들어)이 생성자으로, TYPE의 인스턴스를 전달하여 반사를 방지 할 수 있습니다

+1

대답은 괜찮습니다.하지만 리플렉션을 사용하면 항상 최후의 수단이어야한다고 지적해야합니다. –

+0

은 제네릭과 리플렉션이 같은 것입니까? –

+0

아니요, 아니요, 아니요. 그들은 매우 다릅니다. – Zavior

3

-

public Creator(TYPE a, TYPE b) { 
    this.a = a; 
    this.b = b; 
} 
+0

'newInstance()'가 리플렉션을 사용하는 방법을 설명 할 수 있습니까? – Keerthivasan

+0

[왜 Class.newInstance "evil"입니까?] (http://stackoverflow.com/questions/195321/why-is-class-newinstance-evil) – crush

+0

@Octopus 런타임 검사가 필요하기 때문에 [javadoc ] (http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance%28%29)는 예외 사항에 특히주의하십시오. –

관련 문제