反射获取静态属性

0 概述

如题,通过反射获取java静态属性。

1 代码实现

public class Test {
    private static String test1 = "value1";
    private static String test2 = "value2";

    private static List getStaticField() throws Exception {
        List result = new ArrayList();

        Field[] fields = Test.class.getDeclaredFields();
        if (fields == null || fields.length <= 0) {
            return result;
        }

        for (Field field : fields) {
            field.setAccessible(true);
            //只获取字符串类型
            if (field.getType() == String.class && Modifier.isStatic(field.getModifiers())) {
                result.add(String.valueOf(field.get(Test.class)));
            }
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        for (String str : getStaticField()) {
            System.out.println(str);
        }

    }
}

你可能感兴趣的:(java基础,java)