迭代java中的静态int值 [英] iterate static int values in java
本文介绍了迭代java中的静态int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的问题。有没有办法(使用我想的反射)来迭代一个类的所有静态值?
I have a simple question. Is there a way ( using reflections I suppose ) to iterate all the static values of a class?
例如
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 );
}
}
}
输出
1
2
3
谢谢。
推荐答案
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()]);
}
}
这篇关于迭代java中的静态int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文