日期:2014-05-20  浏览次数:20749 次

如何在子类中获得泛型的具体类型
Parent:
Java code

package test;

public interface Parent<R> {

    public R parentMethod();
}



Child:
Java code

package test;

public interface Child extends Parent<ActualType>{
    
    public ActualType ChildMethod();
}



ActualType:
Java code

package test;

public class ActualType {

}



Test:
Java code

package test;

import java.lang.reflect.Method;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Method [] methods = Child.class.getMethods();
        for(Method method : methods){
            Class<?> clazz = method.getReturnType();
            System.out.println("Method:"+method.getName()+",ReturnType:"+clazz.getName());
        }
    }

}



结果:
Method:ChildMethod,ReturnType:test.ActualType
Method:parentMethod,ReturnType:java.lang.Object
期望结果:
Method:ChildMethod,ReturnType:test.ActualType
Method:parentMethod,ReturnType:test.ActualType

------解决方案--------------------
达不到期望结果的
Java code
public interface Parent<R> { //这个R是泛型,编译时被擦除,
                                 //因为编译器不知道R将被用户赋予什么类型,但又不能不编译,
                                 //所以统一用Object来管理

    public R parentMethod(); //所以这里返回的R就是Object
}

public interface Child extends Parent<ActualType>{ //这个ActualType是具体存在的类型
                                                          //编译时编译器能确定这个具体的类型
    
    public ActualType ChildMethod(); //所以这里返回的就是确定的ActualType
}

------解决方案--------------------
探讨
达不到期望结果的

Java code

public interface Parent<R> { //这个R是泛型,编译时被擦除,
//因为编译器不知道R将被用户赋予什么类型,但又不能不编译,
//所以统一用Object来管理

public……