메서드 인수로 사용할 매개 변수화 된 Class 객체를 얻으려면 어떻게해야합니까?Generics : 매개 변수화 된 클래스 인수 만들기
class A<T>
{
public A(Class<T> c)
{
}
void main()
{
A<String> a1 = new A<String>(String.class); // OK
A<List<String>> a2 = new A<List<String>>(List<String>.class); // error
A<List<String>> a3 = new A<List<String>>(Class<List<String>>); // error
}
}
가 왜 그렇게 싶어, 당신은 요청할 수 있습니다? 다른 매개 변수화 된 클래스가있는 매개 변수화 된 클래스가 있고 해당 생성자가 다른 클래스 형식을 인수로 요구합니다. 런타임 클래스에는 형식 매개 변수에 대한 정보가 없지만 컴파일 타임에이 작업을 수행하지 않아야합니다. 그것은 List<String>.class
과 같은 타입을 지정할 수 있어야합니다. 이 작업을 수행하는 또 다른 구문이 있습니까?
public class Bunch<B>
{
Class<B> type;
public Bunch(Class<B> type)
{
this.type = type;
}
public static class MyBunch<M> extends Bunch<List<M>>
{
Class<M> individualType;
// This constructor has redundant information.
public MyBunch(Class<M> individualType, Class<List<M>> listType)
{
super(listType);
this.individualType = individualType;
}
// I would prefer this constructor.
public MyBunch(Class<M> individualType)
{
super(/* What do I put here? */);
this.individualType = individualType;
}
}
}
가 어떻게이게 가능 : 여기
내 실제 사용 사례입니까?
Google Gson의 'TypeToken'http : //google-gson.googlecode를 보라. co.kr/svn/trunk/gson/docs/javadocs/co.kr/google/gson/reflect/TypeToken.html을 참조하십시오. 그것은 오픈 소스이며 당신이 가진 것과 같은 문제를 해결합니다. – BalusC
가능한 [Java 일반 함수 : 일반 유형을 반환하는 방법] (http://stackoverflow.com/questions/1959022/java-generic-function-how-to-return-generic-type) – BalusC
감사합니다, BalusC. 첫째, 나는 단순한 것을 놓치지 않는다고 안심이됩니다.그러나 ** ** ** ** ** ** ** ** ** ** ** ** 응용 프로그램에서 ** Type ** s를 다루는 것이 어려워 보였으므로이 문제를 해결할 준비가되지 않았습니다. –