Java语法系列之反射

2020-08-19  本文已影响0人  程序员小白成长记

反射在源码中常见的一种语法现象

介绍一个反射demo:
通过反射来实现对象值的set

public class Student {

    private Integer id;
    private String shortId;
    private String name;

    public Student(){

    }

    public Student(Integer id, String shortId, String name) {
        this.id = id;
        this.shortId = shortId;
        this.name = name;

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getShortId() {
        return shortId;
    }

    public void setShortId(String shortId) {
        this.shortId = shortId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {

    public static void main(String[] args) {
        Student student = new Student();
        Class clazz = student.getClass();
        try {
            Method method = clazz.getMethod("setId", Integer.class);
            method.invoke( student, 1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(student.getId());
    }
}

其中Method method = clazz.getMethod("setId", Integer.class); 参数为(方法名变长参数类型列表); method.invoke( student, 1); 参数为(实体,变长参数列表);

output: 1

上一篇下一篇

猜你喜欢

热点阅读