Home  >  Article  >  Java  >  How to read and write fields using Java reflection?

How to read and write fields using Java reflection?

王林
王林forward
2023-04-25 17:25:07608browse

1. Description

(1) Reflection obtains all fields of the Java class, including all fields in the parent class. The fields of the class itself can be directly passed through the method;

(2) Reflection can read and write the fields, use the setX and getX methods to read and write the fields, but pay attention to whether the types before and after reading and writing match, otherwise it will Report exception.

2. Example

    private static int a = 1;
 
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class c = Main.class;
        Field field = c.getDeclaredField("a");
        int b = field.getInt(Main.class);
        System.out.println(b);
        field.setInt(Main.class, 2);
        System.out.println(a);
        field.setFloat(Main.class, (float) 1.1);   // 报异常
    }

What are the basic data types of java

The basic data types of Java are divided into:

1. Integer type, used to represent the data type of integers.

2. Floating point type, a data type used to represent decimals.

3. Character type. The keyword of character type is "char".

4. Boolean type is the basic data type that represents logical values.

The above is the detailed content of How to read and write fields using Java reflection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete