反射如何取得变量和变量的值 从参数object中取值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39184388/article/details/83857830

今天写项目用到了pdf的生成需要从Object中取得传的值填写到pdf中 最后决定使用反射

添加测试类

public class User {
    private Integer id;
    private String name;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
    //省略set get 方法
}
public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    //省略set get 方法
}

1.  如何实现取得所有的值 代码中 getValues(Object object) 这个方法是反射取值的实现

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) throws IllegalAccessException {
        User user = new User(1,"张三");
        Student student = new Student(1,"李四",18);
        // 调用业务 需要在method中使用传入参数的值 然而这个传入的对象可能不同
        // 在该情况下可以使用反射

        System.out.println("传入User");
        method(user);
        System.out.println("传入Student");
        method(student);
    }
    // 模拟业务的方法
    // 因为传入的对象不确定 需要用到Object来接收
    public static void method(Object obj) throws IllegalAccessException {
        List<String> values = getValues(obj);
        // 模拟需要用到参数中属性的值
        System.out.println(values);
    }

    //把传入的参数的值全部取出
    public static List<String> getValues(Object object) throws IllegalAccessException {
        Class clz = object.getClass();
        Field[] field = clz.getDeclaredFields();
        List<String> values = new ArrayList<>();
        for (Field f : field) {
            f.setAccessible(true);
            String value = String.valueOf(f.get(object));
            values.add(value);
        }
        return values;
    }
}

        核心代码 

        

运行结果

2. 如何取得字段呢 

public static List<String> getNames(Object object){
    Class clz = object.getClass();
    Field[] field = clz.getDeclaredFields();
    List<String> names = new ArrayList<>();
    for (Field f : field) {
        String name = f.getName();
        names.add(name);
    }
    return names;
}

        核心代码 

        

结果

如果 属性的值都需要 可以两者结合

猜你喜欢

转载自blog.csdn.net/qq_39184388/article/details/83857830