Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

reflection - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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()]);
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...