Index: lutinutil/src/java/org/codelutin/util/ReflectUtil.java diff -u /dev/null lutinutil/src/java/org/codelutin/util/ReflectUtil.java:1.1 --- /dev/null Sun Dec 30 22:17:47 2007 +++ lutinutil/src/java/org/codelutin/util/ReflectUtil.java Sun Dec 30 22:17:41 2007 @@ -0,0 +1,70 @@ +/* +* ##% Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Code Lutin, +* Tony Chemit +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +* ##% */ +package org.codelutin.util; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +/** + * Des méthodes utiles d'introspection + * + * @author tony + */ +public class ReflectUtil { + /** + * Pour déterminer si un champ d'une classe est une constante + * (modifiers sont static, final et public) + * + * @param field le champs à tester + * @return true si les modifiers sont final, static et public + */ + public static boolean isConstantField(Field field) { + int modifiers = field.getModifiers(); + return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers); + } + + /** + * Recherche dans une classe donnée klazz, les constantes d'un + * certain type searchingClass et les retourne. + * + * @param klass la classe contenant les constantes + * @param searchingClass le type des champs constants à récupérer + * @return la liste des champs du type requis dans + * @throws RuntimeException si problème lors de la récupération + */ + @SuppressWarnings({"unchecked"}) + public static List getConstants(Class klass, Class searchingClass) { + List result = new ArrayList(); + for (Field field : klass.getDeclaredFields()) { + if (!field.isAccessible()) { + field.setAccessible(true); + } + if (searchingClass.isAssignableFrom(field.getType()) && isConstantField(field)) { + try { + result.add((T) field.get(null)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + return result; + } +}