欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > java >内容正文

java

Java反射-继承关系

发布时间:2024/4/13 java 80 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Java反射-继承关系 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

目录

 

反射类型继承关系图

Type   

ParameterizedType

TypeVariable

WildcardType

GenericArrayType

Annotation

AnnotatedElement

GenericDeclaration

AnnotatedType

Parameter 


反射类型继承关系图

Type   

default String getTypeName() {
        return toString();
    }

ParameterizedType

表达一个泛型类型。

Code:

public interface ParameterizedType extends Type {
     //返回泛型类型的实际类型。如果是泛型类型的嵌套非泛型类型,则返回length=0的数组
     //返回的类型是第一层嵌套类型,而不是递归的最基本类型。
     //例如List<Map<String,String>> 返回的是Map<String,String>
    Type[] getActualTypeArguments();

    //返回原始类型,List<String>返回List
    Type getRawType();

    返回类型的拥有者,可以理解嵌套类的外部类。
    Type getOwnerType();
}

Sample

public class GenericTest {

    public List<Map<String, String>> f =new ArrayList<Map<String, String>>();
    public Map<String, String> m =new  HashMap<String, String> ();
    
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, NoSuchFieldException {
        test2();

    }
   
    public static void test2() throws NoSuchMethodException, SecurityException, NoSuchFieldException
    {
        List<Map<String, String>> list =new ArrayList<Map<String, String>>();
        list.add(new HashMap<String, String>());
        
        Class clazz = list.getClass();
        
        ParameterizedType t = (ParameterizedType) clazz.getGenericSuperclass();
        
        Type[] t2 = t.getActualTypeArguments();
        Type t3 = t.getRawType();
        Type t4 = t.getOwnerType();
        
        System.out.println("clazz : " + clazz.getTypeName());
        for(Type t0 : t2 )
        {
            System.out.println("t2 : " + t0.getTypeName()  + " imp:" +   t0.getClass().toString()  );
        }
        
        System.out.println("t3 : " + t3.toString());
        System.out.println("t4 is " + (t4 == null ? " ": " not ") + "null");
        
        
        Field f = GenericTest.class.getDeclaredField("f");
         Type tt = f.getGenericType();
         
         ParameterizedType pt = (ParameterizedType) tt;
        Type[] pt2 = pt.getActualTypeArguments();
        Type pt3 = pt.getRawType();
        Type pt4 = pt.getOwnerType();
        
        System.out.println("clazz : " + pt.getTypeName());
        for(Type t0 : pt2 )
        {
            System.out.println("pt2 : " + t0.getTypeName()  + " imp:" +   t0.getClass().toString()  );
        }
        
        System.out.println("pt3 : " + pt3.toString());
        System.out.println("pt4 is " + (pt4 == null ? " ": " not ") + "null");
        
        
        Field m = GenericTest.class.getDeclaredField("m");
         Type tm = m.getGenericType();
         
         ParameterizedType mpt = (ParameterizedType) tm;
        Type[] mpt2 = mpt.getActualTypeArguments();
        Type mpt3 = mpt.getRawType();
        Type mpt4 = mpt.getOwnerType();
        
        System.out.println("clazz : " + mpt.getTypeName());
        for(Type t0 : mpt2 )
        {
            System.out.println("mpt2 : " + t0.getTypeName() + " imp:" +   t0.getClass().toString()  );
        }
        
        System.out.println("mpt3 : " + mpt3.toString());
        System.out.println("mpt4 is " + (mpt4 == null ? " ": " not ") + "null");
    }
}

Result:

clazz : java.util.ArrayList
t2 : E imp:class sun.reflect.generics.reflectiveObjects.TypeVariableImpl
t3 : class java.util.AbstractList
t4 is  null
clazz : java.util.List<java.util.Map<java.lang.String, java.lang.String>>
pt2 : java.util.Map<java.lang.String, java.lang.String> imp:class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
pt3 : interface java.util.List
pt4 is  null
clazz : java.util.Map<java.lang.String, java.lang.String>
mpt2 : java.lang.String imp:class java.lang.Class
mpt2 : java.lang.String imp:class java.lang.Class
mpt3 : interface java.util.Map
mpt4 is  null

 

TypeVariable

表示类型变量或者又叫类型参数,泛型定义中,<>内的即为类型变量。

Code

public interface TypeVariable<D extends GenericDeclaration> extends Type, AnnotatedElement {
    //返回表示此类型变量上边界的 Type 对象的数组
    //如果未显式声明上边界,则上边界为 Object
    //对于每个上边界 B:

    //如果 B 是一个参数化类型(ParameterizedType) 或一个类型变量(TypeVariable),则会创建它
    //否则,B 将被解析。

    Type[] getBounds();

    // 返回 GenericDeclaration 对象,该对象表示声明此类型变量的一般声明
    D getGenericDeclaration();

    //返回此类型变量的名称,它出现在源代码中
    String getName();

    //Jdk1.8新增的方法,用于获得注解类型的上限,若未明确声明上边界则默认为长度为0的数组。
     AnnotatedType[] getAnnotatedBounds();
}

 

Sample


public class GenericTest {

    public List<Map<String, String>> f =new ArrayList<Map<String, String>>();
    public Map<String, String> m =new  HashMap<String, String> ();
    
    public <T extends Map<String, Integer> & Serializable & Cloneable & Runnable,U extends List<String>> T m2()
    {
        return null;
    }
    
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, NoSuchFieldException {
        test3();

    }
   public static void test3() throws NoSuchMethodException, SecurityException
    {
        Method m = GenericTest.class.getDeclaredMethod("m2");
       TypeVariable<Method>[] vlist =      m.getTypeParameters();
       
      for(TypeVariable<Method> v : vlist)
      {
          System.out.println("getName:" +v.getName());
         Method vm =  v.getGenericDeclaration();
         System.out.println("getGenericDeclaration:" + vm.getName());
        
         Type[] bs = v.getBounds() ;
         for( Type b : bs )
         {
             System.out.println("Bound:" + b.getTypeName());
         }
        
        AnnotatedType[] alist = v.getAnnotatedBounds();
        for(AnnotatedType a : alist )
        {
            java.lang.annotation.Annotation[] annotations = a.getAnnotations();
            for (java.lang.annotation.Annotation annotation : annotations) {
                System.out.println("AnnotatedType" + annotation.toString());
            }
            
            
        }
      }

Result:

getName:T
getGenericDeclaration:m2
Bound:java.util.Map<java.lang.String, java.lang.Integer>
Bound:java.io.Serializable
Bound:java.lang.Cloneable
Bound:java.lang.Runnable
getName:U
getGenericDeclaration:m2
Bound:java.util.List<java.lang.String>

 

WildcardType

Code

public interface WildcardType extends Type {

    Type[] getUpperBounds();
    Type[] getLowerBounds();
}

Sample

    public  <T,U>  Map<T, U> m3(List<? super T> r1,List<? extends U> r2)
    {
        return null;
    }
   

    Method m = GenericTest.class.getDeclaredMethod("m3",List.class,List.class);
       TypeVariable<Method>[] vlist =      m.getTypeParameters();
       

      for(TypeVariable<Method> v : vlist)
      {
          System.out.println("getName:" +v.getName());
         Method vm =  v.getGenericDeclaration();
         System.out.println("getGenericDeclaration:" + vm.getName());
        
         Type[] bs = v.getBounds() ;
         for( Type b : bs )
         {
             System.out.println("Bound:" + b.getTypeName());
         }
        
      }
      
      
       Type[] genericParameterTypes = m.getGenericParameterTypes();
       for (Type type : genericParameterTypes) {
           if (type instanceof ParameterizedType) {
               ParameterizedType parameterizedType = (ParameterizedType) type;
               Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
               for (Type actualType : actualTypeArguments) {
                   if (actualType instanceof WildcardType) {
                       WildcardType wildcardType = (WildcardType) actualType;
                       System.out.println("WildcardType --> " + wildcardType + " getUpperBounds--> "
                               + Arrays.toString(wildcardType.getUpperBounds()) + " getLowerBounds--> " + Arrays.toString(wildcardType.getLowerBounds()));
                   } else {
                       System.out.println("Not WildcardType --> " + actualType);
                   }
               }

           }
       }
      

Result:

getName:T
getGenericDeclaration:m3
Bound:java.lang.Object
getName:U
getGenericDeclaration:m3
Bound:java.lang.Object
WildcardType --> ? super T getUpperBounds--> [class java.lang.Object] getLowerBounds--> [T]
WildcardType --> ? extends U getUpperBounds--> [U] getLowerBounds--> []

 

GenericArrayType

也就是泛型数组,也就是元素类型为泛型类型的数组实现了该接口。它要求元素的类型是ParameterizedType或TypeVariable(实际中发现元素是GenericArrayType也是允许的)

//返回元素类型

Type getGenericComponentType();

Annotation

//返回注解的Class 

Class<? extends Annotation> annotationType();

AnnotatedElement

public interface AnnotatedElement {

    default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
         Objects.requireNonNull(annotationClass);
         // Loop over all directly-present annotations looking for a matching one
         for (Annotation annotation : getDeclaredAnnotations()) {
             if (annotationClass.equals(annotation.annotationType())) {
                 // 做一次强制转化确保确实是同一个Class。
                 return annotationClass.cast(annotation);
             }
         }
         return null;
     }

   
    default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
        Objects.requireNonNull(annotationClass);
        return AnnotationSupport.
            getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()).
                                            collect(Collectors.toMap(Annotation::annotationType,
                                                                     Function.identity(),
                                                                     ((first,second) -> first),
                                                                     LinkedHashMap::new)),
                                            annotationClass);
    }

    //返回定义在类上的注解,包括直接和间接
    Annotation[] getAnnotations();
        
    //返回直接定义在类上的注解
    Annotation[] getDeclaredAnnotations();
    
    <T extends Annotation> T getAnnotation(Class<T> annotationClass);
    
    default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
        return getAnnotation(annotationClass) != null;
    }

    default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
     T[] result = getDeclaredAnnotationsByType(annotationClass);

     if (result.length == 0 && // Neither directly nor indirectly present
         this instanceof Class && // the element is a class
         AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
         Class<?> superClass = ((Class<?>) this).getSuperclass();
         if (superClass != null) {
             // Determine if the annotation is associated with the
             // superclass
             result = superClass.getAnnotationsByType(annotationClass);
         }
     }

     return result;
 }
}

GenericDeclaration

表明可以声明泛型,派生类:Class,Method,Constructor

//返回泛型声明中声明的类型变量

public TypeVariable<?>[] getTypeParameters();

AnnotatedType

泛型相关的类型

public interface AnnotatedType extends AnnotatedElement {
    public Type getType();
}

Sample

public <T, U> Map<T, U> m4(List<? super T> r1, List<? extends U> r2) {
        return null;
    }

    public <T, U> Map<String, String> m5(List<? super T> r1, List<? extends U> r2) {
        return null;
    }

    public static void test5() throws NoSuchMethodException, SecurityException {
        Method m4 = GenericTest.class.getDeclaredMethod("m4", List.class, List.class);
 

        AnnotatedType xx = m4.getAnnotatedReturnType();
        Type yyy = xx.getType();

        Type ttt = m4.getReturnType();

        System.out.println("getAnnotatedReturnType:" + xx.toString()  );
        System.out.println("getAnnotatedReturnType.getType:" + yyy.toString()  );
        System.out.println("getReturnType:" + ttt.toString()  );
        
        Method m5 = GenericTest.class.getDeclaredMethod("m5", List.class, List.class);
 

        AnnotatedType xx5 = m5.getAnnotatedReturnType();
        Type yyy5 = xx5.getType();

        Type ttt5 = m5.getReturnType();
        
        System.out.println("getAnnotatedReturnType:" + xx5.toString()  );
        System.out.println("getAnnotatedReturnType.getType:" + yyy5.toString()  );
        System.out.println("getReturnType:" + ttt5.toString()  );
        
        
    }

Result

getAnnotatedReturnType:sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedParameterizedTypeImpl@6d06d69c
getAnnotatedReturnType.getType:java.util.Map<T, U>
getReturnType:interface java.util.Map
getAnnotatedReturnType:sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedParameterizedTypeImpl@7852e922
getAnnotatedReturnType.getType:java.util.Map<java.lang.String, java.lang.String>
getReturnType:interface java.util.Map

 

Parameter 

定义Executable中的参数

    private final String name;
    private final int modifiers;
    private final Executable executable;
    private final int index;

 

总结

以上是生活随笔为你收集整理的Java反射-继承关系的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。