转载

迭代java中的静态int值

我有一个简单的问题.有没有办法(使用我想的反射)来迭代一个类的所有静态值?

例如

class Any {
    static int one = 1;
    static int two = 2;
    static int three = 3;

    public static void main( String [] args ) {
          for( int i : magicMethod( Any.class ) ){
              System.out.println( i );
          }
    }
 }

产量

谢谢.

import java.util.*;
import java.lang.reflect.*;

class Any {
    static int one = 1;
    static int two = 2;
    static int three = 3;

    public static void main( String [] args ) {
          for( int i : magicMethod( Any.class ) ){
              System.out.println( i );
          }
    }

    public static Integer[] magicMethod(Class<Any> c) {
        List<Integer> list  = new ArrayList<Integer>();
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            try {
                if (field.getType().equals(int.class) && Modifier.isStatic(field.getModifiers())) {
                    list.add(field.getInt(null));
                }
            }
            catch (IllegalAccessException e) {
                // Handle exception here
            }
        }
        return list.toArray(new Integer[list.size()]);
    }
 }

翻译自:https://stackoverflow.com/questions/271109/iterate-static-int-values-in-java

原文  https://codeday.me/bug/20190112/517729.html
正文到此结束
Loading...