An example for you to understand Java reflection mechanism

Reprinted: https://blog.csdn.net/stonesing/article/details/52358288

In layman's terms, the reflection mechanism is to operate a class and its members (functions, properties) as an object ; I hope readers can understand, that is to say, a class, a member of a class, we can also dynamically run to operate them.

package cn.lee.demo;  
  
import java.lang.reflect.Constructor;  
import java.lang.reflect.Field;  
import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;  
import java.lang.reflect.Modifier;  
import java.lang.reflect.TypeVariable;  
  
public class Main {  
    /**
     * In order to see the Java reflection part of the code, I finally throw all exceptions to the virtual machine for processing!
     * @param args
     * @throws ClassNotFoundException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws InvocationTargetException  
     * @throws IllegalArgumentException  
     * @throws NoSuchFieldException  
     * @throws SecurityException  
     * @throws NoSuchMethodException  
     */  
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchFieldException, NoSuchMethodException {  
        // TODO Auto-generated method stub  
          
        //Demo1. Get the package name and class name of the class through the Java reflection mechanism  
        Demo1();  
        System.out.println("===============================================");  
          
        //Demo2. Verify that all classes are instance objects of the Class class  
        Demo2();  
        System.out.println("===============================================");  
          
        //Demo3. Through the Java reflection mechanism, use Class to create class objects [this is the meaning of reflection], no parameter construction  
        Demo3();  
        System.out.println("===============================================");  
          
        //Demo4: Get the constructor of a class through the Java reflection mechanism, and realize the construction of the instance object with parameters  
        Demo4();  
        System.out.println("===============================================");  
          
        //Demo5: Manipulate member variables, set and get through Java reflection mechanism  
        Demo5();  
        System.out.println("===============================================");  
          
        //Demo6: Get some attributes of the class through the Java reflection mechanism: inherited interface, parent class, function information, member information, type, etc.  
        Demo6();  
        System.out.println("===============================================");  
          
        //Demo7: Call the method in the class through the Java reflection mechanism  
        Demo7();  
        System.out.println("===============================================");  
          
        //Demo8: Obtaining class loader through Java reflection mechanism  
        Demo8();  
        System.out.println("===============================================");  
          
    }  
      
    /**
     * Demo1: Get the package name and class name of the class through the Java reflection mechanism
     */  
    public static void Demo1()  
    {  
        Person person = new Person();  
        System.out.println("Demo1: 包名: " + person.getClass().getPackage().getName() + ","   
                + "Full class name: " + person.getClass().getName());  
    }  
      
    /**
     * Demo2: Verify that all classes are instance objects of the Class class
     * @throws ClassNotFoundException  
     */  
    public static void Demo2() throws ClassNotFoundException  
    {  
        //Define two classes of unknown types, set the initial value to null, and see how to assign them to the Person class  
        Class<?> class1 = null;  
        Class<?> class2 = null;  
          
        //Writing 1, may throw ClassNotFoundException [use this writing method more]  
        class1 = Class.forName("cn.lee.demo.Person");  
        System.out.println("Demo2:(写法1) 包名: " + class1.getPackage().getName() + ","   
                + "Full class name: " + class1.getName());  
          
        //Writing 2  
        class2 = Person.class;  
        System.out.println("Demo2:(写法2) 包名: " + class2.getPackage().getName() + ","   
                + "Full class name: " + class2.getName());  
    }  
      
    /**
     * Demo3: Create class objects with Class through the Java reflection mechanism [this is the meaning of reflection]
     * @throws ClassNotFoundException  
     * @throws IllegalAccessException  
     * @throws InstantiationException  
     */  
    public static void Demo3() throws ClassNotFoundException, InstantiationException, IllegalAccessException  
    {  
        Class<?> class1 = null;  
        class1 = Class.forName("cn.lee.demo.Person");  
        //Because there are no parameters here, the class Person you want to instantiate must have a parameterless constructor~  
        Person person = (Person) class1.newInstance();  
        person.setAge(20);  
        person.setName("LeeFeng");  
        System.out.println("Demo3: " + person.getName() + " : " + person.getAge());  
    }  
      
    /**
     * Demo4: Get the constructor of a class through the Java reflection mechanism, and create an instance object with parameters
     * @throws ClassNotFoundException  
     * @throws InvocationTargetException  
     * @throws IllegalAccessException  
     * @throws InstantiationException  
     * @throws IllegalArgumentException  
     */  
    public static void Demo4() throws ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException  
    {  
        Class<?> class1 = null;  
        Person person1 = null;  
        Person person2 = null;  
          
        class1 = Class.forName("cn.lee.demo.Person");  
        // get a set of constructors  
        Constructor<?>[] constructors = class1.getConstructors();  
          
        person1 = (Person) constructors[0].newInstance();  
        person1.setAge (30);  
        person1.setName("leeFeng");  
          
        person2 = (Person) constructors[1].newInstance(20,"leeFeng");  
          
        System.out.println("Demo4: " + person1.getName() + " : " + person1.getAge()  
                + "  ,   " + person2.getName() + " : " + person2.getAge()  
                );  
          
    }  
      
    /**
     * Demo5: Manipulate member variables, set and get through Java reflection mechanism
     *  
     * @throws IllegalAccessException  
     * @throws IllegalArgumentException  
     * @throws NoSuchFieldException  
     * @throws SecurityException  
     * @throws InstantiationException  
     * @throws ClassNotFoundException  
     */  
    public static void Demo5() throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException, InstantiationException, ClassNotFoundException  
    {  
        Class<?> class1 = null;  
        class1 = Class.forName("cn.lee.demo.Person");  
        Object obj = class1.newInstance();  
          
        Field personNameField = class1.getDeclaredField("name");  
        personNameField.setAccessible(true);  
        personNameField.set(obj, "Fat Tiger");  
          
          
        System.out.println("Demo5: Get the value of the property variable after modifying the property: " + personNameField.get(obj));  
          
    }  
      
  
    /**
     * Demo6: Get some properties of the class through the Java reflection mechanism: inherited interface, parent class, function information, member information, type, etc.
     * @throws ClassNotFoundException  
     */  
    public static void Demo6() throws ClassNotFoundException  
    {  
        Class<?> class1 = null;  
        class1 = Class.forName("cn.lee.demo.SuperMan");  
          
        //get parent class name  
        Class<?>  superClass = class1.getSuperclass();  
        System.out.println("Demo6: SuperMan class superclass name: " + superClass.getName());  
          
        System.out.println("===============================================");  
          
          
        Field[] fields = class1.getDeclaredFields();  
        for (int i = 0; i < fields.length; i++) {  
            System.out.println("Members in the class: " + fields[i]);  
        }  
        System.out.println("===============================================");  
          
          
        // get class method  
        Method[] methods = class1.getDeclaredMethods();  
        for (int i = 0; i < methods.length; i++) {  
            System.out.println("Demo6, get the method of SuperMan class: ");  
            System.out.println("函数名:" + methods[i].getName());  
            System.out.println("Function return type: " + methods[i].getReturnType());  
            System.out.println("Function access modifier: " + Modifier.toString(methods[i].getModifiers()));  
            System.out.println("Function code writing: " + methods[i]);  
        }  
          
        System.out.println("===============================================");  
          
        //Get the interface implemented by the class, because the interface class also belongs to the Class, so the method in the interface is the same way to get it  
        Class<?> interfaces[] = class1.getInterfaces();  
        for (int i = 0; i < interfaces.length; i++) {  
            System.out.println("implemented interface class name: " + interfaces[i].getName() );  
        }  
          
    }  
      
    /**
     * Demo7: Invoke class method through Java reflection mechanism
     * @throws ClassNotFoundException  
     * @throws NoSuchMethodException  
     * @throws SecurityException  
     * @throws InvocationTargetException  
     * @throws IllegalAccessException  
     * @throws IllegalArgumentException  
     * @throws InstantiationException  
     */  
    public static void Demo7() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException  
    {  
        Class<?> class1 = null;  
        class1 = Class.forName("cn.lee.demo.SuperMan");  
          
        System.out.println("Demo7: \nCall the parameterless method fly():");  
        Method method = class1.getMethod("fly");  
        method.invoke(class1.newInstance());  
          
        System.out.println("Call the parameterized method walk(int m):");  
        method = class1.getMethod("walk",int.class);  
        method.invoke(class1.newInstance(),100);  
    }  
      
    /**
     * Demo8: Get class loader information through Java reflection mechanism
     *  
     * There are three class loaders in java. [This information is taken from the Internet]
 
        1) Bootstrap ClassLoader This loader is written in C++, which is rare in general development.
 
        2) Extension ClassLoader is used to load extension classes, generally corresponding to the classes in the jre\lib\ext directory
 
        3) AppClassLoader loads the class specified by the classpath and is the most commonly used loader. It is also the default loader in java.
     *  
     * @throws ClassNotFoundException  
     */  
    public static void Demo8() throws ClassNotFoundException  
    {  
        Class<?> class1 = null;  
        class1 = Class.forName("cn.lee.demo.SuperMan");  
        String nameString = class1.getClassLoader().getClass().getName();  
          
        System.out.println("Demo8: class loader class name: " + nameString);  
    }  
      
      
      
}  
/**
 *  
 * @author xiaoyaomeng
 *
 */  
class  Person{  
    private int age;  
    private String name;  
    public Person(){  
          
    }  
    public Person(int age, String name){  
        this.age = age;  
        this.name = name;  
    }  
  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
}  
  
class SuperMan extends Person implements ActionInterface  
{  
    private boolean BlueBriefs;  
      
    public void fly()  
    {  
        System.out.println("Superman can fly~~");  
    }  
      
    public boolean isBlueBriefs() {  
        return BlueBriefs;  
    }  
    public void setBlueBriefs(boolean blueBriefs) {  
        BlueBriefs = blueBriefs;  
    }  
  
    @Override  
    public void walk(int m) {  
        // TODO Auto-generated method stub  
        System.out.println("Superman will walk~" + m + "The rice can't walk anymore!");  
    }  
}  
interface ActionInterface{  
    public void walk(int m);  
}  

I personally think some places to use the reflection mechanism:

1. Factory mode: If reflection is used in the Factory class, after adding a new class, there is no need to modify the factory class Factory
2. The database connection driver is obtained through Class.forName(Driver) in the database JDBC
3. Analysis Class file: After all, you can get the methods in the class, etc.
4. Access some inaccessible variables or properties: crack other people's code



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325506178&siteId=291194637