Java "reflection" study notes

Reflection: Design frame Soul

  • Frame: semi-finished software. Software can be developed on the base frame, a simplified coding

  • Reflection: The various components of the wrapper classes for other objects, this is the reflection

    • benefit:
      1. The program may be during operation , the operation of these objects.
      2. It can be decoupled to improve the program's scalability .
        Here Insert Picture Description
  • Gets the Class object of ways:

    1. Class.forName("全类名"): The byte code file loaded into memory, the object return Class
      • Used for the configuration file , the class name is defined in the configuration file. Read the file, load the class
    2. 类名.class: Get attribute class by class name
      • Used for passing parameters
    3. 对象.getClass(): GetClass () methods defined in the class Object.
      • Used for obtaining the object bytecode manner
public class ReflectDemo1 {


    /**
        获取Class对象的方式:
            1. Class.forName("全类名"):将字节码文件加载进内存,返回Class对象
            2. 类名.class:通过类名的属性class获取
            3. 对象.getClass():getClass()方法在Object类中定义着。

     */
    public static void main(String[] args) throws Exception {

        //1.Class.forName("全类名")
        Class cls1 = Class.forName("cn.itcast.domain.Person");
        System.out.println(cls1);
        //2.类名.class
        Class cls2 = Person.class;
        System.out.println(cls2);
        //3.对象.getClass()
        Person p = new Person();
        Class cls3 = p.getClass();
        System.out.println(cls3);

        //== 比较三个对象
        System.out.println(cls1 == cls2);//true
        System.out.println(cls1 == cls3);//true


        Class c = Student.class;
        System.out.println(c == cls1);//false


    }
}

  • Conclusion: The
    same bytecode files (* .class) during a program is running, it will only be loaded once, regardless of which way acquired by Class objects are the same.
public class Student {
    public void sleep(){
        System.out.println("sleep...");
    }
}
public class Person {
    private String name;
    private int age;

    public String a;
    protected String b;
    String c;
    private String d;


    public Person() {
    }

    public Person(String name, int age) {

        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", a='" + a + '\'' +
                ", b='" + b + '\'' +
                ", c='" + c + '\'' +
                ", d='" + d + '\'' +
                '}';
    }


    public void eat(){
        System.out.println("eat...");
    }

    public void eat(String food){
        System.out.println("eat..."+food);
    }
}
  • Class object function:
    • Acquisition function:
      1. Acquiring member variables are
        • Field [] getFields (): Gets all public member variables modified

        • Field getField (String name) get modified to specify the name of the public member variables

        • Field [] getDeclaredFields () Gets all member variables, regardless of modifiers

        • Field getDeclaredField(String name)

public static void main(String[] args) throws Exception {

        //0.获取Person的Class对象
        Class personClass = Person.class;
        /*
             1. 获取成员变量们
                 * Field[] getFields()
                 * Field getField(String name)

                 * Field[] getDeclaredFields()
                 * Field getDeclaredField(String name)

         */
        //1.Field[] getFields()获取所有public修饰的成员变量
        Field[] fields = personClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        System.out.println("------------");
        //2.Field getField(String name)
        Field a = personClass.getField("a");
        //获取成员变量a 的值
        Person p = new Person();
        Object value = a.get(p);
        System.out.println(value);
        //设置a的值
        a.set(p,"张三");
        System.out.println(p);

        System.out.println("===================");

        //Field[] getDeclaredFields():获取所有的成员变量,不考虑修饰符
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        //Field getDeclaredField(String name)
        Field d = personClass.getDeclaredField("d");
        //忽略访问权限修饰符的安全检查
        d.setAccessible(true);//暴力反射
        Object value2 = d.get(p);
        System.out.println(value2);

    }
  1. Gets constructor who
    • Constructor<?>[] getConstructors()
    • Constructor getConstructor(类<?>… parameterTypes)
    • Constructor getDeclaredConstructor(类<?>… parameterTypes)
    • Constructor<?>[] getDeclaredConstructors()
 public static void main(String[] args) throws Exception {

        //0.获取Person的Class对象
        Class personClass = Person.class;
        /*
            2. 获取构造方法们
                 * Constructor<?>[] getConstructors()
                 * Constructor<T> getConstructor(类<?>... parameterTypes)

                 * Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
                 * Constructor<?>[] getDeclaredConstructors()
         */


        //Constructor<T> getConstructor(类<?>... parameterTypes)
        Constructor constructor = personClass.getConstructor(String.class, int.class);
        System.out.println(constructor);
        //创建对象
        Object person = constructor.newInstance("张三", 23);
        System.out.println(person);

        System.out.println("----------");


        Constructor constructor1 = personClass.getConstructor();
        System.out.println(constructor1);
        //创建对象
        Object person1 = constructor1.newInstance();
        System.out.println(person1);

        Object o = personClass.newInstance();
        System.out.println(o);


        //constructor1.setAccessible(true);
    }

  1. Acquiring member methods are:
    • Method[] getMethods()
    • Method getMethod(String name, 类<?>… parameterTypes)
    • Method[] getDeclaredMethods()
    • Method getDeclaredMethod(String name, 类<?>… parameterTypes)
  2. Get the full class name
    * String getName ()
public static void main(String[] args) throws Exception {

        //0.获取Person的Class对象
        Class personClass = Person.class;
        /*
          3. 获取成员方法们:
             * Method[] getMethods()
             * Method getMethod(String name, 类<?>... parameterTypes)

             * Method[] getDeclaredMethods()
             * Method getDeclaredMethod(String name, 类<?>... parameterTypes)
         */
        //获取指定名称的方法
        Method eat_method = personClass.getMethod("eat");
        Person p = new Person();
        //执行方法
        eat_method.invoke(p);


        Method eat_method2 = personClass.getMethod("eat", String.class);
        //执行方法
        eat_method2.invoke(p,"饭");

        System.out.println("-----------------");

        //获取所有public修饰的方法
        Method[] methods = personClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
            String name = method.getName();
            System.out.println(name);
            //method.setAccessible(true);
        }

        //获取类名
        String className = personClass.getName();
        System.out.println(className);//cn.itcast.domain.Person

    }
  • Field: member variables
    * Operation:
    1. Set value
    * void the SET (Object obj, Object value)
    2. Gets the value
    * GET (Object obj)
    3. ignores access modifiers security checks
    * setAccessible (true): Violence reflection

  • Constructor: constructor
    * Create Object:
    * T the newInstance (Object ... the supplied initargs)
    * If the object is created with an empty argument constructor, the operation can be simplified: newInstance Class object methods

  • Method: Method Object
    * execution method:
    * Object the Invoke (Object obj, Object ... args)
    * acquisition method Name:
    * String getName: acquisition method name

  • Case:

    • Requirements: write down a "framework" and can not change any code in the class of the premise, can help us to create objects of arbitrary classes, and perform any of the method
    • Implementation:
      1. Profile
      2. Reflector
    • Step:
      1. full class name and create the object needs to perform the method defined in the configuration file
      2. In the program reads the configuration file is loaded
      3. reflection technique to load the class files into memory
      4. Create Object
      5. Run method
//pro.properties配置文件
className=cn.itcast.domain.Student
methodName=sleep
/**
 * 框架类
 */
public class ReflectTest {
    public static void main(String[] args) throws Exception {
        //可以创建任意类的对象,可以执行任意方法

        /*
            前提:不能改变该类的任何代码。可以创建任意类的对象,可以执行任意方法
         */
      /*  Person p = new Person();
        p.eat();*/
/*
        Student stu = new Student();
        stu.sleep();*/

        //1.加载配置文件
        //1.1创建Properties对象
        Properties pro = new Properties();
        //1.2加载配置文件,转换为一个集合
        //1.2.1获取class目录下的配置文件
        ClassLoader classLoader = ReflectTest.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("pro.properties");
        pro.load(is);

        //2.获取配置文件中定义的数据
        String className = pro.getProperty("className");
        String methodName = pro.getProperty("methodName");


        //3.加载该类进内存
        Class cls = Class.forName(className);
        //4.创建对象
        Object obj = cls.newInstance();
        //5.获取方法对象
        Method method = cls.getMethod(methodName);
        //6.执行方法
        method.invoke(obj);
    }
}

Published 41 original articles · won praise 1 · views 551

Guess you like

Origin blog.csdn.net/qq_41620020/article/details/105111251