Java tutorial
/*$Id: FieldUtil.java 9779 2008-05-11 15:32:40Z jens $*/ /* **************************************************************************** * * * (c) Copyright 2008 ABM-utvikling * * * * 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. http://www.gnu.org/licenses/gpl.html * * * **************************************************************************** */ package no.abmu.util.reflection; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.LinkedHashSet; import java.util.Set; import no.abmu.util.test.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class provides a set of static methods that * extend the Java meta object protocol, with focus on * fields/variables. * * @author Jens Vindvad, Jens.Vindvad@abm-utvikling.no * @author $Author:jens $ * @version $Rev: 9779 $ * $Date: 2008-05-11 17:32:40 +0200 (Sun, 11 May 2008) $ * copyright ABM-Utvikling * since 2008-05-10 */ public final class FieldUtil { private static final Log logger = (Log) LogFactory.getLog(FieldUtil.class); // Suppress default constructor for noninstantiability. private FieldUtil() { // This constructor will never be invoked. // See Item 3 on page 12 in // Joshua Bloch: Effective Java: Programming Language Guide, 2001 // ISBN 0-201-31005-8 } /** * Returns all fields/variables of object, also all * the inheritages. * * @param obj * @return */ public static Set<Field> getAllValiables(Object obj) { Assert.checkRequiredArgument("obj", obj); Class cls = obj.getClass(); Set<Field> fields = new LinkedHashSet<Field>(); while (cls != null) { Field[] f = cls.getDeclaredFields(); for (int i = 0; i < f.length; i++) { fields.add(f[i]); } cls = cls.getSuperclass(); } return fields; } public static boolean hasObjectVariable(Object obj, String fieldName) { Assert.checkRequiredArgument("obj", obj); Assert.checkRequiredArgument("fieldName", fieldName); return (getField(obj, fieldName) != null); } public static Field getField(Object obj, String fieldName) { Assert.checkRequiredArgument("obj", obj); Assert.checkRequiredArgument("fieldName", fieldName); Field field = null; Set<Field> fieldsInObject = getAllValiables(obj); for (Field fieldInObject : fieldsInObject) { if (fieldName.equals(fieldInObject.getName())) { field = fieldInObject; break; } } return field; } public static boolean setFieldValueToNull(Object obj, String fieldName) { Assert.checkRequiredArgument("obj", obj); Assert.checkRequiredArgument("fieldName", fieldName); String errorMessage = "Object '" + obj.getClass().getName() + " does not have field/variable with name '" + fieldName + "'"; Assert.assertTrue(errorMessage, hasObjectVariable(obj, fieldName)); Field field = getField(obj, fieldName); String fieldType = field.getType().toString(); // This list has to be extended when nessesary // System.out.println("FieldName '" + fieldName + "' has type='" + fieldType + "'"); if (fieldType.equals("int")) { return setFieldValue(obj, fieldName, 0); } else if (fieldType.equals("long")) { return setFieldValue(obj, fieldName, 0); } else if (fieldType.equals("boolean")) { return setFieldValue(obj, fieldName, false); } return setFieldValue(obj, fieldName, null); } public static Object getFieldValue(Object obj, String fieldName) { Assert.checkRequiredArgument("obj", obj); Assert.checkRequiredArgument("fieldName", fieldName); String errorMessage = "Object '" + obj.getClass().getName() + " does not have field/variable with name '" + fieldName + "'"; Assert.assertTrue(errorMessage, hasObjectVariable(obj, fieldName)); Field field = getField(obj, fieldName); Object value = null; try { if (Modifier.isPublic(field.getModifiers())) { value = field.get(obj); } else { field.setAccessible(true); value = field.get(obj); field.setAccessible(false); } } catch (IllegalAccessException e) { logger.error(e.getMessage()); } return value; } public static boolean setFieldValue(Object obj, String fieldName, Object value) { Assert.checkRequiredArgument("obj", obj); Assert.checkRequiredArgument("fieldName", fieldName); String errorMessage = "Object '" + obj.getClass().getName() + " does not have field/variable with name '" + fieldName + "'"; Assert.assertTrue(errorMessage, hasObjectVariable(obj, fieldName)); Field field = getField(obj, fieldName); boolean sucess = false; try { if (Modifier.isPublic(field.getModifiers())) { field.set(obj, value); } else { field.setAccessible(true); field.set(obj, value); field.setAccessible(false); } sucess = true; } catch (IllegalAccessException e) { logger.warn(e.getMessage()); } return sucess; } }