java 反射

 

获取student的class对象

        Class cls = Student.class;

 

反射变量

1.获取所有public的变量

        Field[] fields = cls.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

public java.lang.String Student.name

 

2.获取指定的某个变量

要抛出异常

        Field name = cls.getField("name");
        Student stu=new Student();
        //设置值
        name.set(stu,"tom");
        //读取值
        Object o = name.get(stu);
        System.out.println(o);

tom

 

3.获取所有的变量,包括私有的

Field[] declaredFields = cls.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

private int Student.age
public java.lang.String Student.name

 

4.获取指定的变量,包括私有的

私有的不能直接被访问 : Exception in thread "main" java.lang.IllegalAccessException: class Test cannot access a member of class Student with modifiers "private"

        Field age = cls.getDeclaredField("age");
        //暴力反射
        age.setAccessible(true);
        age.set(stu,99);
        Object o1 = age.get(stu);
        System.out.println(o1);

 

反射构造

       Constructor constructor = cls.getConstructor(int.class, String.class);
        System.out.println(constructor);
        Object o = constructor.newInstance(19, "tom");
        System.out.println(o);

 

反射函数

//反射获得方法 ,参数1传入方法名称 ,参数2类
        Method method = cls.getMethod("ok",String.class);
        System.out.println(method);
        Student stu=new Student();
        //执行方法,参数1对象,参数2方法参数
        method.invoke(stu,"uuuu");

        //获取所有公有方法
        Method[] methods = cls.getMethods();

        //全部方法同理

 

posted @ 2020-07-22 20:50  富坚老贼  阅读(162)  评论(0编辑  收藏  举报