我想收集已经给出类的修饰符的所有字段。我写了以下几段代码:
/**
* Method getFields
* @author TapasB
* @since 03-Nov-2013 - 2:03:17 pm
* @version DAM 1.0
* @param instanceClass
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<Field> getFields(Class<?> instanceClass) {
List<Field> fields = new ArrayList<Field>();
Class<?> searchType = instanceClass;
while (!Object.class.equals(searchType) && searchType != null) {
fields.addAll(Arrays.asList(searchType.getDeclaredFields()));
searchType = searchType.getSuperclass();
}
return Collections.unmodifiableList(new ArrayList(selectDistinct(fields, "name")));
}
/**
* Method getFields
* @author TapasB
* @since 03-Nov-2013 - 2:31:59 pm
* @version DAM 1.0
* @param instanceClass
* @param includedModifiers
* @param excludedModifiers
* @return
*/
public static List<Field> getFields(Class<?> instanceClass, int[] includedModifiers, int[] excludedModifiers) {
List<Field> fields = getFields(instanceClass);
List<Field> filteredFields = new ArrayList<Field>();
if(ArrayUtils.isEmpty(includedModifiers)) {
filteredFields.addAll(fields);
} else {
for(Field field : fields) {
boolean fieldCanBeAdded = false;
for(int includedModifier : includedModifiers) {
if((includedModifier & field.getModifiers()) != 0) {
fieldCanBeAdded = true;
}
}
if(fieldCanBeAdded) {
filteredFields.add(field);
}
}
}
if(ArrayUtils.isNotEmpty(excludedModifiers)) {
Iterator<Field> fieldIterator = filteredFields.iterator();
while (fieldIterator.hasNext()) {
Field field = fieldIterator.next();
boolean fieldNeedsToBeRemoved = false;
for(int excludedModifier : excludedModifiers) {
if((excludedModifier & field.getModifiers()) != 0) {
fieldNeedsToBeRemoved = true;
}
}
if(fieldNeedsToBeRemoved) {
fieldIterator.remove();
}
}
}
return Collections.unmodifiableList(filteredFields);
}
方法getFields(Class<?> instanceClass)
以迭代方式搜索给定类的所有超类的字段,并在Object
处停止。
这里[selectDistinct
] [2]是[LambdaJ API] [3]的方法。它删除父类中也存在于子类中的具有相同名称的字段。
我想知道这是否是实现我想要的好方法。
运行它:
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int[] includedModifiers = new int[]{Modifier.PRIVATE};
int[] excludedModifiers = new int[]{Modifier.FINAL};
List<Field> fields = getFields(ArrayList.class, includedModifiers, excludedModifiers);
for(Field field : fields) {
System.out.println(field.getName());
}
}
main
将仅打印仅包含修饰符private
的字段,并排除private final
。
到目前为止,我发现这个代码没有问题。我只是想知道是否存在更好的解决方案。