java reflection mechanism to explain the core foundation of java

(A) What is a reflection?

It is reflected to the various components of the package as the class of other objects.

Prior to the detailed understanding of reflection, we first look at the process of running java code in the computer:

For example, when we write a good class: Student.java, which contains the student's name and age, construction methods, other methods.

The first stage: Source stage

javac will write our code compiled into .class bytecode files saved on the hard disk, this file holds the class name of the class, member name, constructor, and so on.

The second stage: Class stage

Class object class information into Class file byte code phase will, such as member variables Field, [] storage, with the Constructor constructor [] storage, members method Method, [] Save

The third stage: Runtime stage

By new Student (), according to the Student object class to create the object in the second stage

Here the second phase, the various components of the package is a different object class reflection.

Reflecting benefits:

1 may be the operation target program is running.

2. Decoupling, improve program scalability.

(B) obtaining bytecodes Class object in three ways

Get Class object in three ways, respectively corresponding to the front of the three phases:

A method corresponding to the first stage is to a byte code file is loaded into memory:

class.forname("全类名");

2. The second phase has been generated class class object, therefore as follows:

类名.class;

3. The third stage of the object is generated, as follows:

对象.getclass();

note:

The same bytecode files (.class) during a program run will only be loaded once, class objects created by the above three methods are the same.

By code demonstrates:

New Student category:

public class Student {
    private String name;
    private int age;
    //方便后期测试的成员变量
    public int a;
    public Student(){}
    public Student(String name, int age,int a) {
        this.name = name;
        this.age = age;
        this.a=a;
    }
    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 "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", a=" + a +
                '}';
    }
}

Test objects are three ways to obtain Class

public class reflectTest {
    public static void main(String[] args) throws ClassNotFoundException {
        //方法一
        Class cls1 = Class.forName("com.sdxb.reflect.Student");
        System.out.println(cls1);
        //方法二
        Class cls2 = Student.class;
        System.out.println(cls2);
        //方法三
        Student student=new Student();
        Class cls3 = student.getClass();
        System.out.println(cls3);
        //判断是否是同一对象
        System.out.println(cls1==cls2);
        System.out.println(cls1==cls3);
    }
}

(Iii) Class Gets an object method

1.1 acquiring member variables

Field getField(String name) //获取指定名称public修饰的成员变量
Field[] getFields()  //获取所有public修饰的成员变量
Field getDeclaredField(String name) //获取指定名称成员变量
Field[] getDeclaredFields()  //获取所有成员变量

1.2 operating member variables

Object get(Object obj)  //通过Field获取对象
void set(Object obj, Object value)  //修改Field的值

By code demonstrates

public class FieldTest {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        Class cls = Class.forName("com.sdxb.reflect.Student");
        //1.获取所有public的成员变量
        Field[] fields = cls.getFields();
        for (Field field:fields) {
            System.out.println(field);
        }
        //2.获取指定名字的public成员变量
        Field a = cls.getField("a");
        Student student=new Student();
        //3.操作Field的方法,get和set
        System.out.println(a.get(student));
        a.set(student,10);
        System.out.println(student);
        //4.获取所有成员变量
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field f : declaredFields) {
            System.out.println(f);
        }
    }
}

Here are two methods of operation Field can only operate public variable modified, if need access to other modifiers modified elements will have to add security clearance:

a.setAccessible(true);

2.1 Gets constructor

Constructor<T> getConstructor(Class<?>... parameterTypes)  //根据参数不同获取指定的public构造方法
Constructor<?>[] getConstructors()  //获取所有public构造方法
Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) //根据参数不同获取指定的构造方法
Constructor<?>[] getDeclaredConstructors() //获取所有构造方法

2.2 constructor for

T newInstance(Object... initargs)  //创建对象

By code demonstrates one of two operations:

public class reflectTest2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class cls = Class.forName("com.sdxb.reflect.Student");
        //有参构造方法
        Constructor constructor = cls.getConstructor(String.class, int.class, int.class);
        Object student = constructor.newInstance("sdxb", 24, 1);
        System.out.println(student);
        //无参构造方法
        Constructor constructor2 = cls.getConstructor();
        Object student2 = constructor2.newInstance();
        System.out.println(student2);
        //无参构造方法可以用下面的方式代替
        cls.newInstance();
    }
}

3.1 acquiring member method

Method getMethod(String name, Class<?>... parameterTypes) //根据名称和参数类型获取public方法
Method[] getMethods()  //获取所有public方法
Method getDeclaredMethod(String name, Class<?>... parameterTypes) //根据名称和参数类型获取方法
Method[] getDeclaredMethods()  //获取所有方法

3.2 Method of operation members

Object invoke(Object obj, Object... args)  //执行成员方法

For testing purposes, I added two members of the Student class method:

public void run(){
    System.out.println("run");
}
public void run(int speed){
    System.out.println("run"+speed);
}

Next, test reflection member methods:

public class reflectTest3 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class cls = Student.class;
        Student student=new Student();
        //无参方法
        Method run = cls.getMethod("run");
        run.invoke(student);
        //带参数方法
        Method run2=cls.getMethod("run", int.class);
        run.invoke(student,1);
    }
}

(D) summary

java reflection mechanism in the framework of a wide range of applications, known as the soul of the frame. The reason is that the frame is a semi-finished products, we can not go to class to create the framework defined by the new, thus reflecting played a significant role.

Published 63 original articles · won praise 777 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_41973594/article/details/104095811
Recommended