zoukankan      html  css  js  c++  java
  • 反射之getField()与getDeclaredField()的区别

    遇到Class.getFields(), Class.getField(String), Class.getDeclaredFields(), Class.getDeclaredField(String)

    Class.getMethods(), Class.getMethod(String, Class[]), Class.getDeclaredMethods(), Class.getDeclaredMethod(String, Class[])
    主要的就是有没有Declared单词的区别,使用时有什么不同呢?下面是举一反三的例子!

    父类

    public class Parent {
        public String parent_public;
        protected String parent_protected;
        String parent_default;
        private String parent_private;
    }

    子类

    public class Child extends Parent {
        public String child_public;
        protected String child_protected;
        String child_default;
        private String child_private;
    }

    测试类

    import java.lang.reflect.Field;
    
    public class reflectTest {
        @Test
        public void reflect(){
            System.out.println("getFields()");
            for (Field field : Child.class.getFields()) {
                System.out.println(field.getName());
            }
            System.out.println("---------------");
            System.out.println("getDeclaredFields()");
            for (Field declaredField : Child.class.getDeclaredFields()) {
                System.out.println(declaredField.getName());
            }
        }
    }

    运行结果

    getFields()
    child_public
    parent_public
    ---------------
    getDeclaredFields()
    child_public
    child_protected
    child_default
    child_private

    总结

    getFields()只能获取子类及其父类的public变量。

    get getDeclaredFields()只能获取子类创建的所有变量

  • 相关阅读:
    操作系统:中断和异常
    操作系统
    编程:判断一个点是否在三角形内部
    python 多态
    python super()函数:调用父类的构造方法
    python 继承机制(子类化内置类型)
    python 父类方法重写
    python 继承机制
    python 封装底层实现原理
    python 类的封装
  • 原文地址:https://www.cnblogs.com/kitor/p/12746330.html
Copyright © 2011-2022 走看看