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()只能获取子类创建的所有变量

  • 相关阅读:
    js 运算符优先级
    原生js获取样式
    RGBA 与opacity
    闭包(自己的学习+理解~~水水的)
    css 单位-px、em、rem、百分比
    js之正则1
    querySelector和querySelectorAll
    关于瀑布流的算法(转淘宝ued)
    瀑布流的几个注意点
    jsonp跨域
  • 原文地址:https://www.cnblogs.com/kitor/p/12746330.html
Copyright © 2011-2022 走看看