反射
2021-05-30 14:49 Spiderman25 阅读(90) 评论(0) 收藏 举报

TypeVariable 如class A<T>{}、private <T> method(){}中T就是,实质就是泛型
ParameterizedType List<String> list、private List<String> method(List<String> list) throws MyException<String>{}、class A extends B<String>中3个List<String>和MyException<String>、B<String>都是ParameterizedType,实质就是配上实际类型的类
Type 类型,类型 变量
GenericArrayType 如List<String>[] list、T[],意为TypeVariable、ParameterizedType的数组,getGenericComponentType()可获得实际是哪种
Class 一般类和基本类型都为Class,如String、int、double
WildcardType 泛型表达式 如? extends classA,整个就是
AnnotatedElement 可以被注解的东西
GenericDeclaration 可以定义泛型的东西,如Class Constructor Method
Member 放在类中的成员,如Constructor Method Field
Executable 可执行的东西,如Method Constructor
Constructor
Method
Field
AccessibleObject 可以访问受保护的内容
java.lang.reflect.AnnotatedElement
public abstract <T> T getAnnotation(Class<T> arg0)//根据类对象获取本类及父类中的注解
public abstract Annotation[] getAnnotations()//获取本类及父类中所有注解
public default <T> T[] getAnnotationsByType(Class<T> arg0)//根据类对象获取本类及父类中的所有注解,java8中一个注解可使用多次
public default <T> T getDeclaredAnnotation(Class<T> arg0)//根据类对象获取本类中的注解
public abstract Annotation[] getDeclaredAnnotations()//获取本类中所有注解
public default <T> T[] getDeclaredAnnotationsByType(Class<T> arg0)//根据类对象获取本类中的所有注解,java8中一个注解可使用多次
public default boolean isAnnotationPresent(Class<? extends Annotation> arg0)//是否有注解,如果父类中有@Inherited的注解,则该注解为true
java.lang.reflect.AccessibleObject
public boolean isAccessible()//反射的对象在使用时应该取消 Java 语言访问检查
public static void setAccessible(AccessibleObject[] arg0,boolean arg1) throws SecurityException//值为 false 则指示反射的对象应该实施 Java 语言访问检查
public void setAccessible(boolean arg0) throws SecurityException//值为 false 则指示反射的对象应该实施 Java 语言访问检查
java.lang.reflect.Member
public abstract Class<?> getDeclaringClass()//获取定义该对象的类
public abstract int getModifiers()//获取修饰符
public abstract String getName()//获取名称
public abstract boolean isSynthetic()
java.lang.reflect.GenericDeclaration
public abstract TypeVariable<?>[] getTypeParameters()//获取类型参数列表
java.lang.reflect.TypeVariable
public abstract AnnotatedType[] getAnnotatedBounds()//获取带有注解的泛型上限,如public interface Humen<T extends @CTable(name = "sbsbsbsbbs")CharSequence> {}
public abstract Type[] getBounds()//获取泛型的上限数组,例如<E extends Arrays & Collection>就会获到Arrays、Collection,注:&后必须是接口,前面没要求,
public abstract D getGenericDeclaration()//在哪被定义,类、方法、构造方法
public abstract String getName()//获取名称
java.lang.reflect.Type
public default String getTypeName()//获取类型名称
java.lang.reflect.ParameterizedType
public abstract Type[] getActualTypeArguments()//获类 方法 字段的实际参数类型
public abstract Type getOwnerType()//如果这个类是某个类的内部类,则拥有者就为某个类 Map.Entry<T,U> mapEntry Map为 ownerType,Entry为 rawType, T,U 为实际类
public abstract Type getRawType()//标识原始类,如Response<Person> list的实现类,Response.class即为原始类型
类
public BaseCRUDService() {
try {
Type e = this.getClass().getGenericSuperclass();
if(e instanceof ParameterizedType) {
Class entityClass = (Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
} catch (RuntimeException var2) {
var2.printStackTrace();
}
}
字段
Field[] fields = ParameterizedBean.class.getDeclaredFields();
for(Field f:fields){
if(f.getGenericType() instanceof ParameterizedType){
ParameterizedType pType =(ParameterizedType) f.getGenericType();
System.out.print("变量:"+pType.getTypeName()+" ");
Type[] types =pType.getActualTypeArguments();
for(Type t:types){
System.out.print("类型:"+t.getTypeName());
}
}
类
getGenericInterfaces()
getGenericSuperclass()
字段
getGenericType()
方法
method.getGenericExceptionTypes();
method.getGenericParameterTypes();
method.getGenericReturnType();
java.lang.reflect.GenericArrayType
public abstract Type getGenericComponentType()//获取泛型数组中的元素类型
java.lang.reflect.WildcardType
public abstract Type[] getLowerBounds()//获泛型表达式中的取上限
public abstract Type[] getUpperBounds()//获泛型表达式中的取下限
java.lang.reflect.AnnotatedType
public abstract Type getType()//获取类型,即TypeVariable ParameterizedType GenericArrayType WildcardType Class等
java.lang.reflect.AnnotatedParameterizedType
public abstract AnnotatedType[] getAnnotatedActualTypeArguments()//获类 方法 字段的实际参数类型
java.lang.reflect.AnnotatedTypeVariable
public abstract AnnotatedType[] getAnnotatedBounds()//获取带有注解的泛型上限,如public interface Humen<T extends @CTable(name = "sbsbsbsbbs")CharSequence> {}
java.lang.reflect.AnnotatedArrayType
public abstract AnnotatedType getAnnotatedGenericComponentType()//获取泛型数组中的带有注解的元素类型
java.lang.reflect.AnnotatedWildcardType
public abstract AnnotatedType[] getAnnotatedLowerBounds()//获泛型表达式中带有注解的取上限
public abstract AnnotatedType[] getAnnotatedUpperBounds()//获泛型表达式中带有注解的取下限
AnnotationType总结:
1、在获取到Type的地方都能获取到对应AnnotationType。
2、每个AnnotationType可以获取到对应的Type,从而调用只有Type才有的方法。
3、Type方法获取到的只是Type类型,而AnnotationType方法获取到的是AnnotationType类型。
4、AnnotationType类型继承AnnotationElement从而有获得注解的能力。
5、AnnotationType下面的子类方法一般是Type子类需要获得注解的方法。
java.lang.Class
public <U> Class<? extends U> asSubclass(Class<U> arg0)
public T cast(Object arg0)
public boolean desiredAssertionStatus()
public static Class<?> forName(String arg0) throws ClassNotFoundException
public static Class<?> forName(String arg0,boolean arg1,ClassLoader arg2) throws ClassNotFoundException
public AnnotatedType[] getAnnotatedInterfaces()
public AnnotatedType getAnnotatedSuperclass()
public <A> A getAnnotation(Class<A> arg0)
public <A> A[] getAnnotationsByType(Class<A> arg0)
public String getCanonicalName()
public ClassLoader getClassLoader()
public Class<?>[] getClasses()
public native Class<?> getComponentType()
public Constructor<T> getConstructor(Class<?> arg0) throws NoSuchMethodException,SecurityException
public Constructor<?>[] getConstructors() throws SecurityException
public <A> A getDeclaredAnnotation(Class<A> arg0)
public <A> A[] getDeclaredAnnotationsByType(Class<A> arg0)
public Class<?>[] getDeclaredClasses() throws SecurityException
public Constructor<T> getDeclaredConstructor(Class<?> arg0) throws NoSuchMethodException,SecurityException
public Constructor<?>[] getDeclaredConstructors() throws SecurityException
public Field getDeclaredField(String arg0) throws NoSuchFieldException,SecurityException
public Field[] getDeclaredFields() throws SecurityException
public Method getDeclaredMethod(String arg0,Class<?> arg1) throws NoSuchMethodException,SecurityException
public Method[] getDeclaredMethods() throws SecurityException
public Class<?> getDeclaringClass() throws SecurityException
public Class<?> getEnclosingClass() throws SecurityException
public Constructor<?> getEnclosingConstructor() throws SecurityException
public Method getEnclosingMethod() throws SecurityException
public T[] getEnumConstants()
public Field getField(String arg0) throws NoSuchFieldException,SecurityException
public Field[] getFields() throws SecurityException
public Type[] getGenericInterfaces()
public Type getGenericSuperclass()
public Class<?>[] getInterfaces()
public Method getMethod(String arg0,Class<?> arg1) throws NoSuchMethodException,SecurityException
public Method[] getMethods() throws SecurityException
public native int getModifiers()
public String getName()
public Package getPackage()
public ProtectionDomain getProtectionDomain()
public URL getResource(String arg0)
public InputStream getResourceAsStream(String arg0)
public native Object[] getSigners()
public String getSimpleName()
public native Class<? super T> getSuperclass()
public boolean isAnnotation()
public boolean isAnonymousClass()
public native boolean isArray()
public native boolean isAssignableFrom(Class<?> arg0)
public boolean isEnum()
public native boolean isInstance(Object arg0)
public native boolean isInterface()
public boolean isLocalClass()
public boolean isMemberClass()
public native boolean isPrimitive()
public boolean isSynthetic()
public T newInstance() throws InstantiationException,IllegalAccessException
public String toGenericString()
java.lang.reflect.Executable
public AnnotatedType[] getAnnotatedExceptionTypes()
public AnnotatedType[] getAnnotatedParameterTypes()
public AnnotatedType getAnnotatedReceiverType()
public abstract AnnotatedType getAnnotatedReturnType()
public abstract Class<?>[] getExceptionTypes()
public Type[] getGenericExceptionTypes()
public Type[] getGenericParameterTypes()
public abstract Annotation[][] getParameterAnnotations()
public int getParameterCount()
public abstract Class<?>[] getParameterTypes()
public Parameter[] getParameters()
public boolean isVarArgs()
public abstract String toGenericString()
java.lang.reflect.Method
public Object getDefaultValue()
public Type getGenericReturnType()
public Class<?> getReturnType()
public Object invoke(Object arg0) throws IllegalAccessException,IllegalArgumentException,InvocationTargetException
public boolean isBridge()
public boolean isDefault()
java.lang.reflect.Constructor
public T newInstance() throws InstantiationException,IllegalAccessException,IllegalArgumentException,InvocationTargetException
java.lang.reflect.Field
public Object get(Object arg0) throws IllegalArgumentException,IllegalAccessException
public AnnotatedType getAnnotatedType()
public boolean getBoolean(Object arg0) throws IllegalArgumentException,IllegalAccessException
public byte getByte(Object arg0) throws IllegalArgumentException,IllegalAccessException
public char getChar(Object arg0) throws IllegalArgumentException,IllegalAccessException
public double getDouble(Object arg0) throws IllegalArgumentException,IllegalAccessException
public float getFloat(Object arg0) throws IllegalArgumentException,IllegalAccessException
public Type getGenericType()
public int getInt(Object arg0) throws IllegalArgumentException,IllegalAccessException
public long getLong(Object arg0) throws IllegalArgumentException,IllegalAccessException
public short getShort(Object arg0) throws IllegalArgumentException,IllegalAccessException
public Class<?> getType()
public boolean isEnumConstant()
public void set(Object arg0,Object arg1) throws IllegalArgumentException,IllegalAccessException
public void setBoolean(Object arg0,boolean arg1) throws IllegalArgumentException,IllegalAccessException
public void setByte(Object arg0,byte arg1) throws IllegalArgumentException,IllegalAccessException
public void setChar(Object arg0,char arg1) throws IllegalArgumentException,IllegalAccessException
public void setDouble(Object arg0,double arg1) throws IllegalArgumentException,IllegalAccessException
public void setFloat(Object arg0,float arg1) throws IllegalArgumentException,IllegalAccessException
public void setInt(Object arg0,int arg1) throws IllegalArgumentException,IllegalAccessException
public void setLong(Object arg0,long arg1) throws IllegalArgumentException,IllegalAccessException
public void setShort(Object arg0,short arg1) throws IllegalArgumentException,IllegalAccessException
public String toGenericString()
1 public class MyTest2 { 2 class ClassName implements Comparable<ClassName>{ 3 private String name; 4 private String fullName; 5 6 public ClassName(String name, String fullName) { 7 this.name = name; 8 this.fullName = fullName; 9 } 10 11 public String getName() { 12 return name; 13 } 14 15 public void setName(String name) { 16 this.name = name; 17 } 18 19 public String getFullName() { 20 return fullName; 21 } 22 23 public void setFullName(String fullName) { 24 this.fullName = fullName; 25 } 26 27 @Override 28 public int compareTo(ClassName o) { 29 int i = name.compareTo(o.getName()); 30 if(i==0){ 31 i=fullName.compareTo(o.getFullName()); 32 } 33 return i; 34 } 35 } 36 private String toGenericString(String methodName){ 37 char[] chars = methodName.toCharArray(); 38 StringBuilder sb=new StringBuilder(); 39 boolean pause=false; 40 for (int i = chars.length-1; i >= 0; i--) { 41 char aChar = chars[i]; 42 if(aChar=='.'){ 43 pause=true; 44 }else if(!Character.isLowerCase(aChar)&&!Character.isUpperCase(aChar)){ 45 pause=false; 46 } 47 if(!pause){ 48 sb.append(aChar); 49 } 50 } 51 StringBuilder reverse = sb.reverse(); 52 int i = reverse.indexOf("("); 53 int i1 = reverse.indexOf(")"); 54 String substring = sb.substring(reverse.indexOf("(") + 1, reverse.indexOf(")")); 55 char[] chars1 = substring.toCharArray(); 56 StringBuilder params=new StringBuilder(); 57 //参数个数 58 int paramCount=0; 59 //是否可以加逗号 60 boolean addable=true; 61 for (int i2 = 0; i2 < chars1.length; i2++) { 62 if (chars1[i2]=='<') { 63 addable=false; 64 } 65 if (chars1[i2]=='>') { 66 addable=true; 67 } 68 if(chars1[i2]==','&&addable){ 69 params.append(' ').append("arg"+paramCount++).append(chars1[i2]); 70 }else{ 71 params.append(chars1[i2]); 72 } 73 } 74 if (params.length()>0) { 75 params.append(' ').append("arg"+paramCount++); 76 } 77 return reverse.substring(0,i+1)+params+reverse.substring(i1); 78 } 79 @Test 80 public void test10() throws ClassNotFoundException { 81 //ParameterizedType M 82 Arrays.asList( 83 "java.lang.reflect.Type", 84 "java.lang.reflect.TypeVariable", 85 "java.lang.reflect.ParameterizedType", 86 "java.lang.reflect.GenericArrayType", 87 "java.lang.reflect.WildcardType", 88 "java.lang.reflect.AnnotatedElement", 89 "java.lang.reflect.AccessibleObject", 90 "java.lang.reflect.Member", 91 "java.lang.reflect.GenericDeclaration", 92 "java.lang.reflect.AnnotatedType", 93 "java.lang.reflect.AnnotatedArrayType", 94 "java.lang.reflect.AnnotatedWildcardType", 95 "java.lang.reflect.AnnotatedParameterizedType", 96 "java.lang.reflect.AnnotatedTypeVariable", 97 "java.lang.reflect.Executable", 98 "java.lang.reflect.Method", 99 "java.lang.reflect.Constructor", 100 "java.lang.reflect.Field", 101 "java.lang.Class", 102 "java.util.stream.Collectors", 103 "java.util.stream.Collector", 104 "java.util.stream.Stream", 105 "java.util.Optional", 106 "java.util.Comparator" 107 ).forEach(x-> { 108 try { 109 print1(x); 110 System.out.println(); 111 } catch (ClassNotFoundException e) { 112 e.printStackTrace(); 113 } 114 }); 115 } 116 private void print1(String name) throws ClassNotFoundException { 117 Class<?> aClass = Class.forName(name); 118 Set<Class> superList=new HashSet<>(); 119 Set<Class> interList=new HashSet<>(); 120 getSuperclasss(aClass,superList); 121 getInterfaces(aClass,interList); 122 superList.addAll(interList); 123 Map<String,Method> map=new HashMap<>(); 124 for (Class aClass1 : superList) { 125 List<Method> collect = Arrays.stream(aClass1.getDeclaredMethods()).filter(x -> Modifier.isPublic(x.getModifiers())).collect(Collectors.toList()); 126 for (Method method : collect) { 127 String fullName = getFullName(method); 128 map.put(fullName,method); 129 } 130 } 131 List<Method> collect = Arrays.stream(aClass.getDeclaredMethods()).filter(x->Modifier.isPublic(x.getModifiers())).sorted(Comparator.comparing(Method::getName)).collect(Collectors.toList()); 132 List<Constructor<?>> collect1 = Arrays.stream(aClass.getDeclaredConstructors()).filter(x -> Modifier.isPublic(x.getModifiers())).collect(Collectors.toList()); 133 Set<ClassName> list=new TreeSet<>(); 134 collect.forEach(x->{ 135 if(map.get(getFullName(x))==null){ 136 list.add(new ClassName(x.getName(),toGenericString(x.toGenericString()))); 137 } 138 } 139 ); 140 collect1.forEach(x->{ 141 if(map.get(getFullName(x))==null){ 142 list.add(new ClassName(x.getName(),toGenericString(x.toGenericString()))); 143 } 144 } 145 ); 146 System.out.println(name); 147 list.forEach(x->System.out.println(x.getFullName())); 148 } 149 private <T extends Executable> String getFullName(T method){ 150 int i = method.toGenericString().indexOf("("); 151 int ii = method.toGenericString().indexOf(")"); 152 String substring = method.toGenericString().substring(i , ii+1); 153 String methodName=method.getName()+substring; 154 return methodName; 155 } 156 private void getSuperclasss(Class<?> c,Set<Class> cs){ 157 Class<?> superclass = c.getSuperclass(); 158 if(superclass!=null&&!cs.contains(superclass)){ 159 cs.add(superclass); 160 getSuperclasss(superclass,cs); 161 } 162 } 163 private void getInterfaces(Class<?> c,Set<Class> cs){ 164 Class<?>[] interfaces = c.getInterfaces(); 165 for (Class<?> anInterface : interfaces) { 166 if (!cs.contains(anInterface)) { 167 cs.add(anInterface); 168 getInterfaces(anInterface,cs); 169 } 170 } 171 } 172 }
浙公网安备 33010602011771号