Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate static int values in java

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 {
    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 );
          }
    }
 }

Output

 1
 2
 3

Thanks.

like image 345
OscarRyz Avatar asked Nov 07 '08 02:11

OscarRyz


3 Answers

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()]);
    }
 }
like image 77
Skip Head Avatar answered Nov 18 '22 09:11

Skip Head


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  ) );
          }
      }
like image 4
OscarRyz Avatar answered Nov 18 '22 09:11

OscarRyz


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().

like image 2
Robert Gamble Avatar answered Nov 18 '22 09:11

Robert Gamble