1 package org.jahia.utils; 2 3 import java.lang.reflect.Method ; 4 import java.lang.reflect.InvocationTargetException ; 5 6 14 15 public class BeanTools { 16 17 private static org.apache.log4j.Logger logger = 18 org.apache.log4j.Logger.getLogger(BeanTools.class); 19 20 private BeanTools () { 21 } 22 23 public static boolean setBeanProperty (Object beanObject, 24 String propertyName, 25 Class propertyType, 26 Object propertyValue) { 27 Class beanClass = beanObject.getClass(); 28 String beanMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + 29 propertyName.substring(1); 30 Class [] beanPropertySetterParamTypes = new Class [1]; 31 beanPropertySetterParamTypes[0] = propertyType; 32 try { 33 Method beanPropertySetter = beanClass.getMethod(beanMethodName, beanPropertySetterParamTypes); 34 Object [] args = new Object [1]; 35 args[0] = propertyValue; 36 beanPropertySetter.invoke(beanObject, args); 37 return true; 38 } catch (NoSuchMethodException nsme) { 39 logger.error("Couldn't find setter method " + beanMethodName + " on object " + beanObject, nsme); 40 return false; 41 } catch (IllegalAccessException iae) { 42 logger.error("Error accessing setter method " + beanMethodName + " on object " + beanObject, iae); 43 return false; 44 } catch (InvocationTargetException ite) { 45 logger.error("Exception in setter method " + beanMethodName + " on object " + beanObject, 46 ite.getTargetException()); 47 return false; 48 } 49 } 50 51 public static boolean setBooleanProperty (Object beanObject, 52 String propertyName, 53 String propertyValue) { 54 return setBeanProperty(beanObject, propertyName, Boolean.TYPE, 55 new Boolean (propertyValue)); 56 } 57 58 public static boolean setIntProperty (Object beanObject, 59 String propertyName, 60 String propertyValue) { 61 return setBeanProperty(beanObject, propertyName, Integer.TYPE, 62 new Integer (propertyValue)); 63 } 64 65 public static boolean setLongProperty (Object beanObject, 66 String propertyName, 67 String propertyValue) { 68 return setBeanProperty(beanObject, propertyName, Long.TYPE, 69 new Long (propertyValue)); 70 } 71 72 public static boolean setStringProperty (Object beanObject, 73 String propertyName, 74 String propertyValue) { 75 return setBeanProperty(beanObject, propertyName, String .class, 76 propertyValue); 77 } 78 79 } | Popular Tags |