美文网首页
Java语法系列之反射

Java语法系列之反射

作者: 程序员小白成长记 | 来源:发表于2020-08-19 16:45 被阅读0次

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

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

    • 实体类:Student
    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;
        }
    }
    
    • 反射测试类:Test
    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

    相关文章

      网友评论

          本文标题:Java语法系列之反射

          本文链接:https://www.haomeiwen.com/subject/ruhdjktx.html