B033 Java Learning Notes - Reflection

I. Overview

Reflection-the soul of frame design

1. Framework:

(1) Semi-finished software;

Second, software development can be carried out on the basis of the framework to simplify the code.

(3) The use of frameworks does not require reflection, but they need reflection to develop their own frameworks;

 

2. Reflection:

The reflection mechanism is to encapsulate the components of a class into other objects.

Benefits:

These objects can be manipulated in the process of program running.

(2) Decoupling to improve the extensibility of the program;

 

2. The Method of Obtaining Bytecode class Object

Phase 1 - Source source code phase

Class.forName("full class name"): loads the bytecode file into memory and returns the Class object;

It is mostly used in configuration files, and the class name is defined in the configuration files. Read files, load classes;

2. The second stage - Class class object stage

Class Name. Class: Obtained by the class attribute of the class name;

It is mostly used for parameter transfer.

3. Stage 3 - Runtime runtime

Object. getClass(): getClass() is defined in the Object class;

It is mostly used to acquire bytecode for objects.

4. Code Demonstration

package study.reflect;

import study.method_references.Person;

public class Reflect {
    public static void main(String[] args) throws ClassNotFoundException {
        //Phase 1 - Source source code phase
        //Class.forName("full class name"): loads the bytecode file into memory and returns the Class object;
        Class c1 = Class.forName("study.method_references.Person");
        System.out.println(c1);
        //2. The second stage - Class class object stage
        //Class Name. Class: Obtained by the class attribute of the class name;
        Class c2 = Person.class;
        System.out.println(c2);
        //3. Stage 3 - Runtime runtime
        //Object. getClass(): getClass() is defined in the Object class;
        Person person = new Person();
        Class c3 = person.getClass();
        System.out.println(c3);
        //All three class es are the same
        System.out.println(c1==c2);
        System.out.println(c1==c3);
        //true
        //true
    }
}

Conclusion:

The same bytecode (*. class) file will only be executed once in the process of program execution, regardless of which way the class object obtained is the same;

 

Overview of Class Object Function

Don't forget, first get the class, then get it through the class.

1. Getting member variables

Field[] getFields() (Gets all public member variables)

Returns an array containing some Field objects that reflect all accessible public fields of the class or interface represented by the Class object;

Field getField(String name) (Gets the specified public member variable)

Returns a Field object that reflects the specified public (public-modified) member fields of the class or interface represented by the Class object;

Field [] getDeclared Fields () (Gets all member variables)

Returns an array of Field objects that reflect all fields declared by the class or interface represented by the Class object;

Field getDeclared Field (String name) (Gets the specified member variable)

Returns a Field object that reflects the specified declared fields of the class or interface represented by the Class object.

Code demonstration:

package study.reflect;

import study.method_references.Person;

import java.lang.reflect.Field;

public class GetFieldTest {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //1. Get all public member variables
        Person person = new Person();
        Class c = person.getClass();
        Field[] fields = c.getFields();
        for (Field field : fields) {
            System.out.println(field);
            //public java.lang.String study.method_references.Person.name
        }
        //2. Get the specified public member variable
        Field field = c.getField("name");
        System.out.println(field);
        //public java.lang.String study.method_references.Person.name
        //3. Get the specified member variables (regardless of modifiers)
        Field field1 = c.getDeclaredField("name");
        System.out.println(field1);
        //public java.lang.String study.method_references.Person.name
        Field field2 = c.getDeclaredField("name1");
        System.out.println(field2);
        //private java.lang.String study.method_references.Person.name1
        //4. Get all member variables (regardless of modifiers)
        Field[] fields1 = c.getDeclaredFields();
        for (Field field11 : fields1) {
            System.out.println(field11);
            //private java.lang.String study.method_references.Person.name1
            //public java.lang.String study.method_references.Person.name
        }
        //5. Operating on the acquired variables
        //Get the value
        Person p1 = new Person();
        Object value1 = field.get(p1);
        System.out.println(value1);
        //Setting values
        field.set(p1,"Eldest brother");
        Object value2 = field.get(p1);
        System.out.println(value2);//Eldest brother
    }
}

 

2. Acquisition Construction Method

Constructor<?>[] getConstructors () (Get all common constructors)

Returns an array containing some Constructor objects that reflect all public constructions of the class represented by the Class object;

Constructor < T > getConstructor (Class <?>... parameterTypes) (Get all specified public constructors)

Returns a Constructor object that reflects the specified public constructor of the class represented by the Class object.

Constructor<?>[] getDeclared Constructors () (Get all the constructors)

Returns an array of Constructor objects that reflect all constructive methods of class declarations represented by this Class object.

Constructor < T > getDeclared Constructor (Class <?>... parameterTypes) (Get the specified constructor)

Returns a Constructor object that reflects the specified construction method of the class or interface represented by the Class object.

Code demonstration:

package study.reflect;

import study.method_references.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class GetConstructorsTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //0. Getting classes
        Person person = new Person();
        Class c = person.getClass();
        //1. Obtain all common constructions
        Constructor[] constructors = c.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
            //public study.method_references.Person(java.lang.String)
            //public study.method_references.Person()
        }
        //2. Get all specified public constructors
        Constructor constructor = c.getConstructor(String.class);
        System.out.println(constructor);
        //public study.method_references.Person(java.lang.String)
        //3. Obtain all construction methods
        Constructor[] constructors1 = c.getDeclaredConstructors();
        for (Constructor constructor1 : constructors1) {
            System.out.println(constructor1);
            //private study.method_references.Person(java.lang.String,java.lang.String)
            //public study.method_references.Person(java.lang.String)
            //public study.method_references.Person()
        }
        //4. Get the specified constructor
        Constructor constructor1 = c.getDeclaredConstructor(String.class,String.class);
        System.out.println(constructor1);
        //private study.method_references.Person(java.lang.String,java.lang.String)
        //5. Creating Objects Using Constructive Approaches
        Object p1 = constructor.newInstance("Eldest brother");
        Person p2 = (Person)p1;
        System.out.println(p2.getName());//Eldest brother
        p2.setName("Eldest brother pro");
        System.out.println(p2.getName());//Big Brother pro
    }
}

 

3. Membership acquisition method

Method[] getMethods() (Get all public methods, including those inherited from Object)

Returns an array containing some Method objects that reflect the common (public-modified) member methods of the classes or interfaces represented by the Class object, including those declared by the class or interface and those inherited from the superclass and superinterface;

Method getMethod (String name, Class <?>... parameterTypes) (Get all specified public methods)

Returns a Method object that reflects the specified public (public-modified) member methods of the class or interface represented by the Class object.

Method [] getDeclared Methods () (Get all methods, excluding those inherited from Object)

Returns an array of Method objects that reflect all methods declared by the class or interface represented by the Class object, including public, protected, default (package) access and private methods, but excluding inherited methods;

Method getDeclared Method (String name, Class <?>... parameterTypes) (Get the specified method)

Returns a Method object that reflects the specified declared method of the class or interface represented by the Class object.

Code demonstration:

package study.reflect;

import study.method_references.Person;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class getMethodsTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //0. Getting classes
        Person person = new Person();
        Class c = person.getClass();
        //1. Obtain all public methods
        Method[] methods = c.getMethods();
        for (Method method : methods) {
            System.out.println(method);
            //public java.lang.String study.method_references.Person.getName()
            //public void study.method_references.Person.setName(java.lang.String)
            //public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
            //public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
            //public final void java.lang.Object.wait() throws java.lang.InterruptedException
            //public boolean java.lang.Object.equals(java.lang.Object)
            //public java.lang.String java.lang.Object.toString()
            //public native int java.lang.Object.hashCode()
            //public final native java.lang.Class java.lang.Object.getClass()
            //public final native void java.lang.Object.notify()
            //public final native void java.lang.Object.notifyAll()
        }
        //2. Get all specified public methods
        Method method = c.getMethod("getName");
        System.out.println(method);
        //public java.lang.String study.method_references.Person.getName()
        System.out.println("===============================");
        //3. Obtain all methods
        Method[] methods1 = c.getDeclaredMethods();
        for (Method method1 : methods1) {
            System.out.println(method1);
            //public java.lang.String study.method_references.Person.getName()
            //public void study.method_references.Person.setName(java.lang.String)
            //private java.lang.String study.method_references.Person.getName1()
            //private void study.method_references.Person.setName1(java.lang.String)
        }
        //4. Getting the specified method
        Method method1 = c.getDeclaredMethod("getName1");
        System.out.println(method1);
        //private java.lang.String study.method_references.Person.getName1()
        //5. Calling methods
        Person p = new Person();
        //Private approach, violent reflex
        method1.setAccessible(true);
        method1.invoke(p);//getName1 is executed...
    }
}

 

4. Get the class name

String getName()

Returns the name of the entity (class, interface, array class, basic type or void) represented by this Class object in the form of String.

Code demonstration:

package study.reflect;

import study.method_references.Person;

public class getNameTest {
    public static void main(String[] args) {
        //0. Getting classes
        Person person = new Person();
        Class c = person.getClass();
        //1. Get the class name
        String className = c.getName();
        System.out.println(className);//study.method_references.Person
    }
}

 

IV. CASES

1. Demand

Write a "framework" in which any class can be created and any method can be invoked without changing the code of the class.

 

2. Realization Analysis

Configuration file + reflection;

 

3. Implementation steps

The full class name of the object to be created and the method to be executed are defined in the configuration file.

(2) Loading configuration files in programs;

(3) Using reflection technology to load class files into memory;

(4) Creating objects;

(5) Execution method;

 

4. Code Demonstration

Students:

package study.reflect;

public class Student {
    public void study(){
        System.out.println("Learn...");
    }
    public void sleep(){
        System.out.println("Sleep...");
    }
}

Test class:

package study.reflect;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class DemoTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //The full class name of the object to be created and the method to be executed are defined in the configuration file.

        //(2) Loading configuration files in programs;
        //Create Properties
        Properties properties = new Properties();
        //Get the class loader
        ClassLoader classLoader = DemoTest.class.getClassLoader();
        //Reading configuration files using class loaders
        InputStream inputStream = classLoader.getResourceAsStream("pro.properties");
        //Converting a configuration file into a Properties collection
        properties.load(inputStream);
        //(3) Using reflection technology to load class files into memory;
        String className = properties.getProperty("className");
        String methodName = properties.getProperty("methodName");
        Class c = Class.forName(className);
        //(4) Creating objects;
        Object o = c.getDeclaredConstructor().newInstance();
        //(5) Execution method;
        Method method = c.getMethod(methodName);
        method.invoke(o);
        //Sleep...
    }
}

 

 

 

 

 

 

 

 

Keywords: Java Attribute

Added by valleydr on Tue, 30 Jul 2019 06:46:48 +0300