• java的反射


    1.获取反射Class类的方式

    Class.forName("全类名");

    类名.class//需要在JVM已加载的前提下

    对象.getClass

    2.java对javabean进行操作的四种方式

    public class Descriptor {
    
            public static void main(String[] args) throws Exception {
    
                   // 方式1
    
                   PropertyDescriptor descriptor = new PropertyDescriptor("x", TestDemo1.class);
    
                   Method readMethod = descriptor.getReadMethod();
    
                   TestDemo1 testDemo1 = new TestDemo1();
    
                   Object invoke = readMethod.invoke(testDemo1);
    
                   if (invoke instanceof String) {
    
                           System.out.println((String) invoke);
    
                   }
    
                   // 方式2 这个方法只能得到所有的方法
    
                   BeanInfo beanInfo = Introspector.getBeanInfo(TestDemo1.class);
    
                   PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
    
                   for (PropertyDescriptor propertyDescriptor : descriptors) {
    
                           if (propertyDescriptor.getName().equals("x")) {
    
                                   System.out.println(propertyDescriptor.getName());
    
                           }
    
                   }
    
                   // 方式3
    
                   Class testClass = TestDemo1.class;
    
                   Object newInstance = testClass.newInstance();
    
                   if (newInstance instanceof TestDemo1) {
    
                           System.out.println(((TestDemo1) newInstance).getX());
    
                   }
    
                   // 方式4
    
                   Class testClass1 = Class.forName("cn.reflect.collection.TestDemo1");
    
                   Field declaredField = testClass1.getDeclaredField("x");
    
                   if (!declaredField.isAccessible()) {
    
        //类似与上判断是否是公有的属性
    
        // if(!Modifier.isPublic(declaredField.getModifiers())){
    
                           declaredField.setAccessible(true);
    
                   }
    
                    System.out.println(declaredField.get(testDemo1));
    
            }
    
    }
    
    class TestDemo1 {
            private String x = "qwe";
    
            public String getX() {
                   return x;
            }
    
            public void setX(String x) {
                   this.x = x;
            }
    
    }
    

    3.利用反射获取注解

    //RetentionPolicy  枚举  RetentionPolicy.RUNTIME 运行时起作用,必须使用运行时才能够反射
    
    @Retention(RetentionPolicy.RUNTIME)//元注解
    
    // ElementType 枚举 ElementType.TYPE 修饰于类,接口,枚举,注解
    
    @Target(ElementType.TYPE)
    
    @interface ReflectAnnotationdemo1 {
    
            // value可以省略 value= ,省略的前提是只有
    
            String value();
    
    }
    
    @ReflectAnnotationdemo1("111")
    
    class AnnotationDemo1 {
    
    }
    
     public class AnnotationDemo {
    
            public static void main(String[] args) {
    
                   AnnotationDemo1 annotationDemo1 = new AnnotationDemo1();
    
                   Class<? extends AnnotationDemo1> class1 = annotationDemo1.getClass();
    
                   if (class1.isAnnotationPresent(ReflectAnnotationdemo1.class)) {
    
                           ReflectAnnotationdemo1 annotation = class1.getAnnotation(ReflectAnnotationdemo1.class);
    
                           System.out.println(annotation.value());
    
                   }
    
            }
    
    }
    

    4.对泛型的反射

    public class ReflectGenericity {
    	private static final String ParameterizedType = null;
    
    	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
    		//获取父类的参数化类型
    		Type genericSuperclass = ReflectGenericityTest1.class.getGenericSuperclass();
    		if (genericSuperclass instanceof ParameterizedType) {
    			Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments();
    			System.out.println(actualTypeArguments[0]);
    		}
    		//获取类型
    		Method[] methods = ReflectGenericityTest.class.getMethods();
    		for (int i = 0; i < methods.length; i++) {
    			if(methods[i].getName().equals("test1")){
    				Parameter[] parameters = methods[i].getParameters();
    				System.out.println(parameters[0]);
    				break;
    			}
    		}
    		//获取参数化类型
    		Method method = ReflectGenericityTest.class.getMethod("test2", Vector.class);
    		Type[] genericParameterTypes = method.getGenericParameterTypes();
    		System.out.println(genericParameterTypes[0]);
    	}
    }
    
    class ReflectGenericityTest<T> {
    	public static <E> E test1(E e) {
    		return e;
    	}
    	public static void test2(Vector<String> e) {
    	}
    }
    
    class ReflectGenericityTest1<T> extends ReflectGenericityTest<T> {
    }
    

     5.反射的工具类

    public class ReflectUtils {
    	public static Class getSuperClass(Class clazz, int index) {
    		Type gentype = clazz.getGenericSuperclass();
    		if (!(gentype instanceof ParameterizedType)) {
    			return Object.class;
    		}
    		Type[] params = ((ParameterizedType) gentype).getActualTypeArguments();
    		if (index >= params.length || index < 0) {
    			return Object.class;
    		}
    		if (!(params[index] instanceof Class)) {
    			return Object.class;
    		}
    		return (Class) params[index];
    	}
    
    	public static <T> Class<T> getSupergType(Class clazz) {
    		return getSuperClass(clazz, 0);
    	}
    
    	public static Method getDecaredMethod(Object obj, String methoname, Class<?>[] paraterty) {
    		for (Class clazz = obj.getClass(); clazz != Object.class; clazz.getSuperclass()) {
    			try {
    				return clazz.getDeclaredMethod(methoname, paraterty);
    			} catch (Exception e) {
    				
    			}
    		}
    		return null;
    	}
    
    	public static void makeAccsible(Field field) {
    		// getmodifys获取各种权限的叠加整型
    		if (Modifier.isPublic(field.getModifiers())) {
    			field.setAccessible(true);
    		}
    	}
    
    	public static Field getDecaredMethod(Object obj, String fieldname) {
    		for (Class clazz = obj.getClass(); clazz != Object.class; clazz.getSuperclass()) {
    			try {
    				return clazz.getDeclaredField(fieldname);
    			} catch (Exception e) {
    				
    			}
    		}
    		// ArrayList<Object> arrayList = new ArrayList<String>();
    		return null;
    	}
    
    	public static Object invokeMethod(Object obj, String methoname, Class<?>[] paraterty, Object[] parame) {
    		Method method = getDecaredMethod(obj, methoname, paraterty);
    		if (method == null) {
    			throw new IllegalAccessError();
    		}
    		if (Modifier.isPublic(method.getModifiers())) {
    			method.setAccessible(true);
    		}
    		try {
    			method.invoke(obj, parame);
    		} catch (Exception e) {
    			
    		}
    		return null;
    	}
    
    	public static void setFieldValue(Object obj, String fieldname, Object param) {
    		Field field = getDecaredMethod(obj, fieldname);
    		if (field == null) {
    			throw new IllegalAccessError();
    		}
    		makeAccsible(field);
    		try {
    			field.set(obj, param);
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		}
    	}
    
    	public static Object geyFieldValue(Object object, String name) {
    		Field field = getDecaredMethod(object, name);
    		if (field == null) {
    			throw new IllegalArgumentException("not find field!");
    		}
    		try {
    			field.get(object);
    		} catch (IllegalAccessException e) {
    			
    		}
    		return null;
    	}
    }
    

     6.多态反射获取的字节码是对象自身的字节码文件,也可以这么认为多态的字节码是对象本身

    public class ReflectPoly implements ReflectPolyFather {
        public static void main(String[] args) {
            ReflectPolyFather reflectPoly = new ReflectPoly();
            // 获得class文件是其对象的class文件
            System.out.println(reflectPoly.getClass().getName());// cn.reflect.demo.ReflectPoly
    
        }
    
        @Override
        public void test() {
            System.err.println("test");
        }
    }
    
    interface ReflectPolyFather {
        public abstract void test();
    
    }
  • 相关阅读:
    (作业3)Linux内核的启动过程(从start_kernel到init进程启动)
    (作业2)mykernel实验指导(操作系统是如何工作的)
    (作业1)将一个简单的C程序编译成汇编代码,讨论计算机是如何工作的进行
    中国大学MOOC-数据结构基础习题集、09-3、Hashing
    中国大学MOOC-数据结构基础习题集、09-2、QQ帐户的申请与登陆
    中国大学MOOC-数据结构基础习题集、09-1、Hashing
    中国大学MOOC-数据结构基础习题集、08-3、Sort with Swap(0,*)
    中国大学MOOC-数据结构基础习题集、08-2、The World's Richest
    中国大学MOOC-数据结构基础习题集、08-1、Talent and Virtue
    中国大学MOOC-数据结构基础习题集、07-2、Insert or Merge
  • 原文地址:https://www.cnblogs.com/gg128/p/9311210.html
Copyright © 2020-2023  润新知