反射学习笔记

/**
 * @description 通过一个对象获得完整的包名和类名
 */
publicclassTestReflect {
      public static void main(String[] args) throws Exception {
             TestReflect testReflect = new TestReflect();
             System.out.println(testReflect.getClass().getName());
             // 结果reflect.TestReflect(包名.类名)
         }
}
/**
 * @description 获取某个类的全部属性
 */
public class TestReflectProperty implements Serializable{
     private static final long serialVersionUID = -2862585049955236662L;
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("reflect.TestReflectProperty");
        System.out.println("===============本类属性===============");
        // 取得本类的全部属性
        Field[] field = clazz.getDeclaredFields();
        for (int i = 0; i < field.length; i++) {
            // 权限修饰符
            int mo = field[i].getModifiers();
            String priv = Modifier.toString(mo);
            // 属性类型
            Class<?> type = field[i].getType();
            System.out.println(priv + " " + type.getName() + " " + field[i].getName() + ";");
        }
        
        System.out.println("==========实现的接口或者父类的属性==========");
        // 取得实现的接口或者父类的属性
        Field[] filed1 = clazz.getFields();
        for (int j = 0; j < filed1.length; j++) {
            // 权限修饰符
            int mo = filed1[j].getModifiers();
            String priv = Modifier.toString(mo);
            // 属性类型
            Class<?> type = filed1[j].getType();
            System.out.println(priv + "1 " + type.getName() + " " + filed1[j].getName() + ";");
        }
    }
}
/**
 * @description 实例化class三种方式
 */
public class InstantiationReflect {
     public static void main(String[] args) throws Exception {
        Class<?> class1 = null;
        Class<?> class2 = null;
        Class<?> class3 = null;
        // 一般采用这种形式
        class1 = Class.forName("reflect.InstantiationReflect");
        class2 = new InstantiationReflect().getClass();
        class3 = InstantiationReflect.class;
        System.out.println("类名称   " + class1.getName());
        System.out.println("类名称   " + class2.getName());
        System.out.println("类名称   " + class3.getName());
    }
}
/**
 * @description 通过反射机制调用某个类的方法
 */
public class MethodReflect {
     public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("reflect.MethodReflect");
        // 调用 MethodReflect类中的reflect1方法
        Method method = clazz.getMethod("reflect1");
        method.invoke(clazz.newInstance());
        // Java 反射机制 - 调用某个类的方法1.
        // 调用 MethodReflect的reflect2方法
        method = clazz.getMethod("reflect2", int.class, String.class);
        method.invoke(clazz.newInstance(), 20, "张三");
        // Java 反射机制 - 调用某个类的方法2.
        // age -> 20. name -> 张三
    }
    public void reflect1() {
        System.out.println("Java 反射机制 - 调用某个类的方法1.");
    }
    public void reflect2(int age, String name) {
        System.out.println("Java 反射机制 - 调用某个类的方法2.");
        System.out.println("age -> " + age + ". name -> " + name);
    }
}
/**
 * @description 通过反射机制修改某个类的属性
 */
public class PropertyReflectTest {
     private String proprety = null;
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("reflect.PropertyReflectTest");
        Object obj = clazz.newInstance();
        // 可以直接对 private 的属性赋值
        Field field = clazz.getDeclaredField("proprety");
        field.setAccessible(true);
        field.set(obj, "Java反射机制");
        System.out.println(field.get(obj));
    }
}
/**
 * @description 通过反射获取当前类的父类以及实现接口
 */
public class ReflectImpl implements Serializable {
     private static final long serialVersionUID = -2862585049955236662L;
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("reflect.ReflectImpl");
        // 取得父类
        Class<?> parentClass = clazz.getSuperclass();
        System.out.println("clazz的父类为:" + parentClass.getName());
        // clazz的父类为: java.lang.Object
        // 获取所有的接口
        Class<?> intes[] = clazz.getInterfaces();
        System.out.println("clazz实现的接口有:");
        for (int i = 0; i < intes.length; i++) {
            System.out.println((i + 1) + ":" + intes[i].getName());
        }
        // clazz实现的接口有:
        // 1:java.io.Serializable
    }
}
/**
 * @description 在泛型为Integer的ArrayList中存放一个String类型的对象。
 */
public class ArrayReflect {
     public static void main(String[] args) throws Exception {
        ArrayList<Integer> list = new ArrayList<Integer>();
        Method method = list.getClass().getMethod("add", Object.class);
        method.invoke(list, "Java反射机制实例。");
        System.out.println(list.get(0));
    }
}
/**
 * @description 通过反射取得并修改数组的信息
 */
public class UpdateArrayReflect {
     public static void main(String[] args) throws Exception {
        int[] temp = { 1, 2, 3, 4, 5 };
        Class<?> demo = temp.getClass().getComponentType();
        System.out.println("数组类型: " + demo.getName());
        System.out.println("数组长度  " + Array.getLength(temp));
        System.out.println("数组的第一个元素: " + Array.get(temp, 0));
        Array.set(temp, 0, 100);
        System.out.println("修改之后数组第一个元素为: " + Array.get(temp, 0));
    }
}
/**
 * @description 通过反射机制修改数组的大小
 */
public class UpdateArraySize {
     public static void main(String[] args) throws Exception {
        int[] temp = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int[] newTemp = (int[]) arrayInc(temp, 15);
        print(newTemp);
        String[] atr = { "a", "b", "c" };
        String[] str1 = (String[]) arrayInc(atr, 8);
        print(str1);
    }
    // 修改数组大小
    public static  Object  arrayInc(Object obj, int len) {
        Class<?> arr = obj.getClass().getComponentType();
        Object newArr = Array.newInstance(arr, len);
        int co = Array.getLength(obj);
        System.arraycopy(obj, 0, newArr, 0, co);
        return newArr;
    }
    // 打印
    public  static  void  print(Object obj) {
        Class<?> c = obj.getClass();
        if (!c.isArray()) {
            return;
        }
        System.out.println("数组长度为: " + Array.getLength(obj));
        for (int i = 0; i < Array.getLength(obj); i++) {
            System.out.print(Array.get(obj, i) + " ");
        }
        System.out.println();
    }
}
/**
 * @description 将反射机制应用于工厂模式
 */
public class FactoryReflectTest {
     public static void main(String[] args) throws Exception {
        fruit f = Factory.getInstance("reflect.Apple");
        if (f != null) {
            f.eat();
        }
    }
}
interface fruit {
    public abstract void eat();
}
class Apple implements fruit {
    public void eat() {
        System.out.println("Apple");
    }
}
class Orange implements fruit {
    public void eat() {
        System.out.println("Orange");
    }
}
class Factory {
    public static fruit getInstance(String ClassName) {
        fruit f = null;
        try {
            f = (fruit) Class.forName(ClassName).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}
/**
 * @description 反射机制的动态代理
 */
public class TestReflectTest {
     public static void main(String[] args) throws Exception {
        MyInvocationHandler demo = new MyInvocationHandler();
        Subject sub = (Subject) demo.bind(new RealSubject());
        String info = sub.say("Rollen", 20);
        System.out.println(info);
    }
}
//定义项目接口
interface Subject {
  public String say(String name, int age);
}
//定义真实项目
class RealSubject implements Subject {
  public String say(String name, int age) {
      return name + "  " + age;
  }
}
class MyInvocationHandler implements InvocationHandler {
  private Object obj = null;
  public Object bind(Object obj) {
      this.obj = obj;
      return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
  }
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      Object temp = method.invoke(this.obj, args);
      return temp;
  }
}
业精于勤,荒于嬉;行成于思,毁于随;
原文地址:https://www.cnblogs.com/freedom-yuxin/p/7459800.html