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

How to read and write fields using Java reflection?

王林
Release: 2023-04-25 17:25:07
forward
726 people have browsed it

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);   // 报异常
    }
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template