iterate static int values in java

后端 未结 5 1238
感动是毒
感动是毒 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:31

    Hey.. it was very easy. :P

          Field [] constants = Main.class.getFields();
          Object some = new Main();
          for( Field field : constants ){
              if(Modifier.isStatic(field.getModifiers() ) && 
                 field.getType() == int.class  ) {
                        System.out.println( field.getInt( some  ) );
              }
          }
    
    0 讨论(0)
  • 2020-12-19 05:42

    Your solution works for public fields but not private fields like you have in your example. If you want to be able to access the private fields of a class you need to use getDeclaredFields() instead of getFields().

    0 讨论(0)
  • 2020-12-19 05:42

    You could do something like this:

    import java.lang.reflect.*;
    
    public class Foo {
    
    public static int one = 1;
    public static int two = 2;
    public static int three = 3;
    
    public static void magicMethod( Class clz ) throws Exception {
        Field[] fields = clz.getFields();
        System.out.println(""+fields);
        for( Field field : fields ) {
            int modifiers = field.getModifiers();
            if( ! Modifier.isStatic(modifiers) )
                continue;
            System.out.println("" + field.get(null));
        }
    }
    
    public static void main(String[] args) throws Exception {
        Foo.magicMethod( Foo.class );
    }}
    

    It's important to note, however, that the fields have to be public for this to work. It's not exactly what you asked, but it should be close enough that you should be able to make it work for what you need. Obviously this doesn't do any kind of error handling or anything so you should make sure that you handle any errors or exceptions in your real application.

    0 讨论(0)
  • 2020-12-19 05:43

    As an alternative, use an enum and get rid of the class variables entirely (to be precise, the enum is a class variable as well :-)):

    class Any {
        enum Number {
            ONE(1),
            TWO(2),
            THREE(3);
    
            Number(int number) {
                this.number = number;
            }
    
            int number;
        };
    
        public static void main(String [] args) {
            for (Number value : Number.values()) {
                System.out.println(value.number);
            }
        }
    }
    
    0 讨论(0)
  • 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<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()]);
        }
     }
    
    0 讨论(0)
提交回复
热议问题