iterate static int values in java

后端 未结 5 1257
感动是毒
感动是毒 2020-12-19 05:09

I have a simple question. Is there a way ( using reflections I suppose ) to iterate all the static values of a class?

For instance

class Any {
    s         


        
5条回答
  •  鱼传尺愫
    2020-12-19 05:45

    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 c) {
            List list  = new ArrayList();
            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()]);
        }
     }
    

提交回复
热议问题