『阿男的Java泛型讲座』*07*Wildcard的类反射(补充内容)

本节课视频:

『阿男的Java泛型讲座』*07*Wildcard的类反射(补充内容)

本节课代码:

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author <a href="mailto:[email protected]">Weinan Li</a>
 */
public class WildcardReflection2 {

    public static void reverse(List<?> list) {  // equals to <? extends Object>
    }

    public static void main(String[] args) throws Exception {
        Method reverse = WildcardCapture.class.getMethod("reverse", List.class);
        System.out.println(reverse);

        Type paramType = reverse.getGenericParameterTypes()[0];
        System.out.println("paramType: " + paramType.getClass() + " -> " + paramType);
        if (paramType instanceof ParameterizedType) {
            Type actualType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
            System.out.println("actualType: " + actualType.getClass() + " -> " + actualType);
        }
    }
}


代码输出:

public static void lang.WildcardCapture.reverse(java.util.List)
paramType: class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl -> java.util.List<?>
actualType: class sun.reflect.generics.reflectiveObjects.WildcardTypeImpl -> ?

你可能感兴趣的:(java)