Java learning notes 18 - Reflection

Posted by lutzlutz896 on Fri, 14 Jan 2022 00:32:16 +0100

What is reflection?

java reflection mechanism is to know all the properties and methods of any class in the running state; For any object, you can call any of its methods and properties; This kind of dynamically acquired information and the function of dynamically calling object methods are called the reflection mechanism of java language (the only dynamic mechanism of java).  

 1. Implementation function of reflection

① judge the class of any object at runtime;

② construct the object of any class at runtime;

③ judge the member variables and methods of any class at run time;

④ call the method of any object at runtime;

⑤ generate dynamic agent;

2. Get the source class (key)

Class < T > an instance of class type can be used to represent a type during java operation. This class instance can be understood as a class model, which contains the structure information of the class.

How to get the (source of reflection) Class object:

                                 1. Class name class              

                                 2. Class. Forname: package name Class name -- > recommended

                                 3. Object getClass()

Note: Class objects exist after the Class is loaded into memory for the first time. They are unique and unchanged. There is only one for each type

The Class object can manipulate all the contents of this Class (attribute method constructor...)

//Example code - three ways to get the Class object reflecting the original header
public class Class002_Reflect {
    public static void main(String[] args) throws ClassNotFoundException {
        //1. Class name class
        Class<String> cls1 = String.class;
        System.out.println(cls1.toString());

        //2.Class. Forname (permission naming)
        Class cls2 = Class.forName("java.lang.String");
        System.out.println(cls2);

        //3. Object getClass()
        Class cls3 = "abc".getClass();
        System.out.println(cls3);

        //Gets the Class object of the parent Class of the type represented by the current Class object
        Class cls4 = cls1.getSuperclass();
        System.out.println(cls4);

        //Gets the Class object of the basic data type
        System.out.println(Integer.class);
        System.out.println(int.class);
        System.out.println(int.class==Integer.class);
        System.out.println(Integer.TYPE);
        System.out.println(Integer.TYPE==int.class);
    }
}

3. Constructor

According to the Class object, we can obtain the constructor to prepare for instantiating the object

Constructor<T>

Getconstructor (class <? >... Parametertypes)

Returns a Constructor object that reflects the specified public function of the class represented by the Constructor object

Constructor<?>[]

getConstructors()

Returns all public Constructor class objects that contain an array Constructor object that reflects the class represented by it

        

//Instance code - get constructor by creating Class object
public class Class003_Reflect {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        //Get constructor (only public constructors modified by public can be obtained)
        Class<User> cls = User.class;
        Constructor[] cons =  cls.getConstructors();
        for(Constructor con:cons){
            System.out.println(con);
        }
        //Gets an array of constructor objects that reflect all constructors declared by the class represented by such objects (including those private in the class)
        Constructor<User> con = cls.getDeclaredConstructor(String.class,int.class);
        System.out.println(con);

        //create object
        //1)
        User user =  User.class.newInstance();
        System.out.println(user);
        //2) Private content needs to ignore permission usage
        con.setAccessible(true);  //Ignore permissions
        User user2 = con.newInstance("laopei",1234);
        System.out.println(user2);
    }
}
class User{
    private String name;
    private int pwd;
    //Public
    public User() {
    }
    public User(String name) {
        this.name = name;
    }
    //Private
    private User(String name, int pwd) {
        this.name = name;
        this.pwd = pwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getPwd() {
        return pwd;
    }
    public void setPwd(int pwd) {
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", pwd=" + pwd +
                '}';
    }
}

4. Instantiate object

There are three ways to create objects: new, clone, deserialization, and another. According to the Class object, use newInstance() or constructor to instantiate the object.

T newInstance() the null structure of the default call type is object initialization information -- > not recommended

(Note: it is uncertain whether a type has an empty structure, and it is very likely to encounter runtime exceptions)

T newInstance(Object... initargs) calls the current constructor to initialize information for the object while creating the object

 5. Properties and methods

Get all properties (including parent class or interface), and use field to operate. Field is used as the object describing the property.

         Field                  getDeclaredField(String nname)

Returns a Field object that reflects the specified declared Field of the class or interface represented by this class object

         Field[ ]               getDeclaredFields( )

The returned array Field object reflects all fields declared by the class or interface represented by this class object

         Field                  getField(String name)

Returns a Field object that reflects the specified public member Field of the class or interface represented by this class object

         Field[ ]               getFields( )

Returns a Field object containing an array that reflects all public fields and class objects of the class or interface represented by it

Get all methods (including parent classes or interfaces) and use method. Method is the object that describes the method

  • The method getMethod(String name, class <? >... Parametertypes) returns a method object that reflects the specified public member method of the class or interface represented by this kind of object.
  • The method [] getMethods() returns an array containing method objects that reflect all public methods of the class or interface represented by such objects, including those declared by the class or interface and those inherited from the superclass and superinterface.
  • The method getdeclaraedmethod (string name, class <? >... Parametertypes) returns a method object that reflects the specified declared method of the class or interface represented by this kind of object.
  • The method [] getdeclaraedmethods() returns an array containing method objects that reflect all declared methods of the class or interface represented by such objects, including public, protected, default (package) access and private methods, but excluding inherited methods.
//Example code - reflection operation properties and methods
public class Class004_Reflect {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        User user = new User("zhangsan");
        //Class object of User class
        Class<User> cls = User.class;
        testMethod(cls,user);
    }
    //test method
    public static void testMethod(Class<User> cls,User user) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method[] methods = cls.getMethods();
        for(Method m:methods){
            System.out.println(m);
        }
        //Private method
        Method method = cls.getDeclaredMethod("haha",int.class);
        //Call method
        method.setAccessible(true);
        System.out.println(method.invoke(user,100));;
        System.out.println(method.invoke(null,100));;
        Method m = cls.getMethod("getName");
        System.out.println(m.invoke(user));
    }
    //Test properties
    public static void testField(Class<User> cls,User user) throws NoSuchFieldException, IllegalAccessException {
        Field field = cls.getDeclaredField("name");
        System.out.println(field.getName());
        System.out.println(field.getType());
        //Ignore permissions
        field.setAccessible(true);
        field.set(user,"zhangsanfeng");
        System.out.println(field.get(user));
    }
}

6. Reflection operation array

The Array class is required to manipulate arrays.

  • Static object newinstance (class <? > componenttype, int length) creates a new array with the specified component type and length.
  • static Object get(Object array, int index) returns the value of the index component in the specified array object.
  • static void set(Object array, int index, Object value) sets the value of the index component of the specified array object to the specified new value.
//Example code - reflection operation array
public class Class005_Reflect {
    public static void main(String[] args) throws Exception {
        //Call method
        testArray();
        test(String.class);
    }
    public static void test(Class<String> cls){
        //int getModifiers() returns the Java language modifiers of this class or interface, encoded as integers.
        System.out.println(cls.getModifiers());
        System.out.println(Modifier.toString(cls.getModifiers()));

        //Class <? > [] getinterfaces() returns the interface directly implemented by the class or interface represented by this object.
        System.out.println(Arrays.toString(cls.getInterfaces()));

        //String getName() returns the entity name (class, interface, array class, basic type or void) represented by this kind of object as a string.
        System.out.println(cls.getName());

        //String getSimpleName() returns the simple name of the base class given in the source code.
        System.out.println(cls.getSimpleName());
    }

    //Simple operation array
    public static void testArray(){
        int[] arr = (int[]) Array.newInstance(int.class,5);
        Array.set(arr,2,200);
        System.out.println(Arrays.toString(arr));
        System.out.println(Array.get(arr,2));
    }
}

 

Topics: Java Back-end reflection