反射使用方法

获取.class对象的三种方式

  • Class c = Class.forName("java.lang.String");// 最常用
  • Class c = Person.class; // 在同一个包中使用
  • String s = new String("1");
    Class c = s.getClass(); // 任何对象都可以通过这个方法获取所属类对象

通过class对象的属性和方法

获取类属性

  • 获取全部属性:Field[] f = c.getDeclaredFields();
  • 获取指定属性:Field f = c.getDeclaredField("name"); // 使用反射访问私有变量时,需要提前打破封装性,不推荐
    修改属性: Field f = c.getField("sex"); Object obj = c.newInstance(); f.set(obj, "男"); // set方法修改
  • 获取全部方法:string.getDeclaredMethods()
  • 获取指定方法:

获取修饰

  • 获取访问控制符:Modifier.toString(string.getModifiers())
  • 获取类名属性名方法名:f.getName()
  • 获取方法返回值:m.getReturnType()
  • 获取数据类型:m.getType()

获取构造方法

Class c = Class.forName("reflect.fruit.Apple");
		Constructor con = c.getConstructor(String.class); //传入要获取的构造函数参数的.class参数
		Object o = con.newInstance("red"); // 使用构造函数对象创建对象

使用反射调用类的方法

        //获取方法
        Method method = c.getDeclaredMethod("m5", String.class, int.class);
        //创建对象
        Object o = c.newInstance();
        Object result = method.invoke(o, "admin", 10);

泛型擦除

		List<Integer> list = new ArrayList<>(); // 泛型只在编译时起作用		
		Class c = list.getClass();
		java.lang.reflect.Method m = c.getMethod("add", Object.class); // 使用反射在运行过程中得到List的list方法,默认的add方法添加的是Object对象
		m.invoke(list, "abcd");
		m.invoke(list, new Person());
		System.out.println(list);
原文地址:https://www.cnblogs.com/zhz-8919/p/10822235.html