Framework: semi-finished software, which can be developed on the basis of framework and simplify coding

Reflection: Encapsulating the components of a class into other objects is the mechanism of reflection

Benefits: * You can manipulate these objects while the program is running. * Can be decoupled, improve the scalability of the program.Copy the code

1. Basic Concepts

In reflection, it is also possible to get the complete structure of a class by reflection, using the following classes in the java.lang.Reflect package:

Constructor: indicates the Constructor of a class. Field: indicates the attributes of a class. Method: indicates the methods of a classCopy the code

These three classes are all subclasses of AccessibleObject:

interface China{
    public static final String NATIONAL = "China";
    public static final String AUTHOR = "Java";
    public void sayChina(a);// Define an abstract method with no parameters
    public String sayHello(String name,int age);// Define an abstract method with parameters
}
class Person implements China{
    private String name;
    private int age;
    public Person(a){}public Person(String name){// Declare a constructor for one argument
        this.name = name;
    }
    public Person(String name,int age){
        this(name);
        this.setAge(age);
    }

    public String getName(a) {
        return name;
    }

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

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

    @Override
    public void sayChina(a) {
        System.out.println("Author:" + AUTHOR + Nationality: + NATIONAL);
    }

    @Override
    public String sayHello(String name, int age) {
        return name + "Hello! I this year" + age + "Age!; }}Copy the code

Two, to achieve all the interface

To obtain all interfaces implemented by a Class, we must use the getInterfaces() method of the Class Class, which defines:

public Class[] getInterfaces()
Copy the code

The getInterfaces() method returns an array of objects of the Class, which is then output directly using the getName() method of the Class.

public class Root{
    public static void main(String[] args) { Class<? > c1 =null;// Declare the Class object
        try{
            c1 = Class.forName("Person");
        }catch(ClassNotFoundException e){ e.printStackTrace(); } Class<? > c[] = c1.getInterfaces();// Get all the interfaces implemented
        for (int i=0; i<c.length; i++){ System.out.println("Implemented interface name:" + c[i].getName());// Output interface name}}}Copy the code

Because an interface is a special form of a Class, and a Class can implement multiple interfaces, all interface objects are returned in the form of a Class array, and the contents are output in a loop

Get the parent class

A Class can implement multiple interfaces, but can only inherit one parent Class. To get a parent Class, use the getSuperclass() method of the Class Class. This method defines:

public Class<? super T> getSuperclass()
Copy the code

The getSuperclass() method returns an instance of the Class, and as with the previous interface, you can get the name from the getName() method.

public class Test{
    public static void main(String[] args) { Class<? > c1 =null;
        try {
            c1 = Class.forName("Person");
        }catch(ClassNotFoundException e){ e.printStackTrace(); } Class<? > c2 = c1.getSuperclass();// Get the parent information
        System.out.println("Parent name:"+ c2.getName()); }}Copy the code

The Person class is written without explicitly inheriting from a parent class, so it inherits from the Object class by default

Fourthly, obtain all construction methods

To get all constructors in a Class, you must use the getConstructors() method of the Class Class.

  1. Gets all the constructors of the Person class
import java.lang.reflect.Constructor;

public class Test{
    public static void main(String[] args) { Class<? > c1 =null;
        try {
            c1 = Class.forName("Person");
        }catch(ClassNotFoundException e){ e.printStackTrace(); } Constructor<? > con[] = c1.getConstructors();// Get all the constructors
        for (int i=0; i<con.length; i++){ System.out.println("Construction method:"+ con[i]); }}}Copy the code
  1. Gets all the constructors of a class
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

public class Test{
    public static void main(String[] args) { Class<? > c1 =null;
        try {
            c1 = Class.forName("Person");
        }catch(ClassNotFoundException e){ e.printStackTrace(); } Constructor<? > con[] = c1.getConstructors();// Get all the constructors
        for (int i=0; i<con.length; i++){ Class<? > p[] = con[i].getParameterTypes();// Lists the parameter types in the construct
            System.out.print("Construction method:");
            int mo = con[i].getModifiers();// Access permission
            System.out.print(Modifier.toString(mo) + "");// Restore permissions
            System.out.print(con[i].getName());// Prints the constructor name
            System.out.print("(");
            for (int j=0; j<p.length; j++){ System.out.print(p[j].getName() +" arg" + i);
                if (j<p.length-1) {// Print the parameter type to determine whether to print ","
                    System.out.print(",");
                }
            }
            System.out.println("{}"); }}}Copy the code

Five, get all the methods

To get all the methods in a Class, use the Class ClassgetMethods()Method, which returns an array of objects of the Method class. Common methods of this method:

Get all method definitions of a class:

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Test{
    public static void main(String[] args) { Class<? > c1 =null;
        try {
            c1 = Class.forName("Person");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        Method m[] = c1.getMethods();// Get all the methods
        for (int i=0; i<m.length; i++){ Class<? > r = m[i].getReturnType();// Retrieve the return value type of the methodClass<? > p[] = m[i].getParameterTypes();// Get all the argument types
            int xx = m[i].getModifiers();// Get the modifier for the method
            System.out.print(Modifier.toString(xx) + "");// Restore the modifier
            System.out.print(r.getName() + "");// Get the method name
            System.out.print(m[i].getName());// Get the method name
            System.out.print("(");
            for (int x=0; x<p.length; x++){ System.out.print(p[x].getName() +"" + "arg" + x);// Output parameters
                if (x<p.length-1){
                    System.out.print(",");// determine whether to print ","} } Class<? > ex[] = m[i].getExceptionTypes();// Get all exceptions thrown
            if (ex.length>0){
                System.out.print(") throws ");// Outputs ") throws"
            }else {
                System.out.print(")");
            }
            for (int j=0; j<ex.length; j++){ System.out.print(ex[j].getName());// Output abnormal information
                if (j<ex.length-1){
                    System.out.print(","); } } System.out.println(); }}}Copy the code

Development tools take advantage of reflection

Get all attributes

It is also possible to obtain all attributes of a class in a reflection operation. There are two different operations:

Get a public property in the implemented interface or superclass:public Field[] getFields() throwsSecurityException gets all the attributes in this class:public Field[] getDeclareDeclaredFields() throws SecurityException
Copy the code

The above methods return an array of fields. Each Field object represents an attribute in the class. To obtain further information about the attribute, use:Gets an attribute from the Person class

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Test{
    public static void main(String[] args) { Class<? > c1 =null;
        try {
            c1 = Class.forName("Person");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        {// Plain code block
            Field f[] = c1.getDeclaredFields();// Get this class attribute
            for (int i=0; i<f.length; i++){ Class<? > r = f[i].getType();// Get the type of the attribute
                int mo = f[i].getModifiers();// Get the modifier number
                String priv = Modifier.toString(mo);// Get the modifier for the property
                System.out.print("Attributes of this class:");
                System.out.print(priv + "");// Output modifiers
                System.out.print(r.getName() + "");// Output attribute type
                System.out.print(f[i].getName());// Output the attribute name
                System.out.println(";");/ / a newline
            }
        }
        System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = =");
        {
            Field f[] = c1.getFields();// Get the parent public attribute
            for (int i=0; i<f.length; i++){ Class<? > r = f[i].getType();// Get the type of the attribute
                int mo = f[i].getModifiers();// Get the modifier number
                String priv = Modifier.toString(mo);// Get the property modifier
                System.out.print("Public property:");
                System.out.print(priv + "");// Output modifiers
                System.out.print(r.getName() + "");// Output parameter type
                System.out.print(f[i].getName());// Output the attribute name
                System.out.println(";"); }}}}Copy the code