By accessing Java reflection member variables

Field will return an object or array type member variable is accessed when any of the following method.

	getFields()
	
	getField(String name)
	
	getDeclaredFields()
	
	getDeclaredField(String name)

Field object represents the above-mentioned method returns a member variable. For example, to access a member variable name for the price, the sample code as follows:

object.getDeciaredField("price");

Field class common method

Method name Explanation
getName() Get the name of the member variable
getType() Gets a member variable of the Class object
get(Object obj) Member variable to obtain the value of the specified object obj, the return value of type Object
set(Object obj, Object value) The value of the specified object obj as the value of the member variables
getlnt(0bject obj) The value of the specified object obj members of type int member variables
setlnt(0bject obj, int i) The value of the specified object obj in the member variable is i
setFloat(Object obj, float f) The value of the specified object obj member variables is f
getBoolean(Object obj) For the specified object obj members of type boolean value of a member variable of
setBoolean(Object obj, boolean b) The value of the specified object obj in the member variable is b
getFloat(Object obj) The value of the specified object obj members of type float member variables
setAccessible(boolean flag) This method can set the member variable is ignored direct access to private rights and other proprietary rights
getModifiers() Can be obtained by parsing the method uses the integer modifier

Examples of how to call a method of obtaining information Field class dynamic class individual members.

1. First create a Book class, the class in order to declare a String, int, float, and members of the boolean type, and set different access scope. Book final class code is as follows:

public class Book {
    String name;
    public int id;
    private float price;
    protected boolean isLoan;
}

2) preparation of test class Test, reflected by all members of the class Book access class in the main () method, and outputs the member name and type information to the console.

Test class code as follows:

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class Test {
    public static void main(String[] args) {
        Book book = new Book();
        // 获取动态类Book
        Class class1 = book.getClass();
        // 获取Book类的所有成员
        Field[] declaredFields = class1.getDeclaredFields();
        // 遍历所有的成员
        for(int i = 0;i < declaredFields.length;i++) {    
            // 获取类中的成员变量
            Field field = declaredFields[i];
            System.out.println("成员名称为:" + field.getName());
            Class fieldType = field.getType();
            System.out.println("成员类型为:" + fieldType);
            boolean isTurn = true;
            while(isTurn) {
                try {    
                    // 如果该成员变量的访问权限为private,则抛出异常
                    isTurn = false;
                    System.out.println("修改前成员的值为:" + field.get(book));
                    // 判断成员类型是否为int
                    if(fieldType.equals(int.class)) {
                        System.out.println("利用setInt()方法修改成员的值");
                        field.setInt(book, 100);
                    } else if(fieldType.equals(float.class)) {    
                        // 判断成员变量类型是否为float
                        System.out.println("利用setFloat()方法修改成员的值");
                        field.setFloat(book, 29.815f);
                    } else if(fieldType.equals(boolean.class)) {    
                        // 判断成员变量是否为boolean
                        System.out.println("利用setBoolean()方法修改成员的值");
                        field.setBoolean(book, true);
                    } else {
                        System.out.println("利用set()方法修改成员的值");
                        field.set(book, "Java编程");
                    }
                    System.out.println("修改后成员的值为:" + field.get(book));
                } catch (Exception e) {
                    System.out.println("在设置成员变量值时抛出异常,下面执行setAccessible()方法");
                    field.setAccessible(true);
                    isTurn = true;
                }
            }
            System.out.println("=============================\n");
        }
    }
}

3. Run the test class Test, the program will turn dynamic access to all the members of the Book class. Access to name members of the operating results are as follows:

成员名称为:name
成员类型为:class java.lang.String
修改前成员的值为:null
利用set()方法修改成员的值
修改后成员的值为:Java编程
=============================

Access id members operating results are as follows:

成员名称为:id
成员类型为:int
修改前成员的值为:0
利用setInt()方法修改成员的值
修改后成员的值为:100
=============================

Access price members operating results are as follows:

成员名称为:price
成员类型为:float
在设置成员变量值时抛出异常,下面执行setAccessible()方法
修改前成员的值为:0.0
利用setFloat()方法修改成员的值
修改后成员的值为:29.815
=============================

Access isLoan members operating results are as follows:

成员名称为:isLoan
成员类型为:boolean
修改前成员的值为:false
利用setBoolean()方法修改成员的值
修改后成员的值为:true
=============================
Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104728554