/** * Creates an instance of the class using the default constructor. * * @since 0.2.06 */ @SuppressWarnings("cast") private static <T> T newInstanceFromDefaultConstructor(Class<T> type) { if (type == null) return null; if (logger.isDebugEnabled()) logger.debug("Instantiating " + type.getSimpleName()); if (deprecated(type)) escalator.escalate( "Instantiating a deprecated class: " + type.getName(), BeanUtil.class, null); try { return (T) type.newInstance(); } catch (InstantiationException e) { throw ExceptionMapper.configurationException(e, type); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, type); } }
/** * Returns the bean property descriptor of an attribute * * @param beanClass the class that holds the attribute * @param propertyName the name of the property * @return the attribute's property descriptor */ public static PropertyDescriptor getPropertyDescriptor(Class<?> beanClass, String propertyName) { if (beanClass == null) throw new IllegalArgumentException("beanClass is null"); String propertyId = beanClass.getName() + '#' + propertyName; PropertyDescriptor result = propertyDescriptors.get(propertyId); if (result != null) return result; // descriptor is new int separatorIndex = propertyName.indexOf('.'); if (separatorIndex >= 0) { String localProperty = propertyName.substring(0, separatorIndex); String remoteProperty = propertyName.substring(separatorIndex + 1); Class<?> localPropertyType = getPropertyDescriptor(beanClass, localProperty).getPropertyType(); result = getPropertyDescriptor(localPropertyType, remoteProperty); } else { try { BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : descriptors) { String name = descriptor.getName(); if (name.equals(propertyName)) { result = descriptor; break; } } } catch (IntrospectionException e) { throw ExceptionMapper.configurationException(e, propertyName); } } propertyDescriptors.put(propertyId, result); return result; }
/** * Instantiates the specified class. * * @param name the name of the class to instantiate * @return the Class instance */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> Class<T> forName(String name) { Assert.notNull(name, "class name"); Class type = simpleTypeMap.get(name); if (type != null) return type; else { try { return (Class<T>) getContextClassLoader().loadClass(name); } catch (ClassNotFoundException e) { throw ExceptionMapper.configurationException(e, name); } catch (NullPointerException e) { // this is raised by the Eclipse BundleLoader if it does not find the class throw ExceptionMapper.configurationException(e, name); } } }
/** * Sets an attribute value of an object. * * @param obj the object to modify * @param field the attribute to set * @param value the value to assign to the field */ private static void setAttributeValue(Object obj, Field field, Object value) { try { field.set(obj, value); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, field); } }
/** * Returns a Field object that represents an attribute of a class * * @param type the class that holds the attribute * @param name the name of the attribute * @return a Field object that represents the attribute */ public static Field getField(Class<?> type, String name) { try { return type.getField(name); } catch (NoSuchFieldException e) { throw ExceptionMapper.configurationException(e, type.getName() + '.' + name); } }
public static <T> T newInstance( Constructor<T> constructor, boolean strict, Object... parameters) { if (!strict) parameters = convertArray(parameters, constructor.getParameterTypes()); Class<T> type = constructor.getDeclaringClass(); if (deprecated(type)) escalator.escalate( "Instantiating a deprecated class: " + type.getName(), BeanUtil.class, null); try { return constructor.newInstance(parameters); } catch (InstantiationException e) { throw ExceptionMapper.configurationException(e, type); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, type); } catch (InvocationTargetException e) { throw ExceptionMapper.configurationException(e, type); } }
/** * Returns a class' static attribute value * * @param objectType the class to query * @param attributeName the name of the attribute * @return the attribute value */ public static Object getStaticAttributeValue(Class<?> objectType, String attributeName) { Field field = getField(objectType, attributeName); try { return field.get(null); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, field); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public static Object invoke(Object target, Method method, boolean strict, Object... args) { try { Object[] params; Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0) { params = null; } else if (args.length == paramTypes.length) { // map one to one if (strict) { params = args; } else { params = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { Object arg = args[i]; if (arg == null) params[i] = null; else { Converter converter = ConverterManager.getInstance().createConverter(arg.getClass(), paramTypes[i]); params[i] = converter.convert(arg); } } } } else { // map varargs params = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length - 1; i++) params[i] = (strict ? args[i] : AnyConverter.convert(args[i], paramTypes[i])); Class<?> varargsComponentType = paramTypes[paramTypes.length - 1].getComponentType(); Object varargs = Array.newInstance(varargsComponentType, args.length - paramTypes.length + 1); for (int i = 0; i < args.length - paramTypes.length + 1; i++) { Object param = args[paramTypes.length - 1 + i]; if (strict) param = AnyConverter.convert(param, varargsComponentType); Array.set(varargs, i, param); } params[params.length - 1] = varargs; } return method.invoke(target, params); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, method); } catch (InvocationTargetException e) { throw ExceptionMapper.configurationException(e, method); } }
public static Object getPropertyValue(Object bean, String propertyName, boolean strict) { Method readMethod = null; try { PropertyDescriptor descriptor = getPropertyDescriptor(bean.getClass(), propertyName); if (descriptor == null) { if (strict) throw new ConfigurationError( "Property '" + propertyName + "' not found in class " + bean.getClass()); else return null; } readMethod = descriptor.getReadMethod(); return readMethod.invoke(bean); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, readMethod); } catch (InvocationTargetException e) { throw ExceptionMapper.configurationException(e, readMethod); } }
/** * Returns an object's attribute value * * @param obj the object to query * @param attributeName the name of the attribute * @return the attribute value */ public static Object getAttributeValue(Object obj, String attributeName) { if (obj == null) throw new IllegalArgumentException("Object may not be null"); Field field = getField(obj.getClass(), attributeName); try { return field.get(obj); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, field); } }
public static void setPropertyValue( Object bean, String propertyName, Object propertyValue, boolean required, boolean autoConvert) { Method writeMethod = null; try { Class<?> beanClass = bean.getClass(); PropertyDescriptor propertyDescriptor = getPropertyDescriptor(beanClass, propertyName); if (propertyDescriptor == null) if (required) throw new ConfigurationError( beanClass + " does not have a property '" + propertyName + "'"); else return; writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod == null) throw new UnsupportedOperationException( "Cannot write read-only property '" + propertyDescriptor.getName() + "' of " + beanClass); Class<?> propertyType = propertyDescriptor.getPropertyType(); if (propertyValue != null) { Class<?> argType = propertyValue.getClass(); if (!propertyType.isAssignableFrom(argType) && !isWrapperTypeOf(propertyType, propertyValue) && !autoConvert) throw new IllegalArgumentException( "ArgumentType mismatch: expected " + propertyType.getName() + ", found " + propertyValue.getClass().getName()); else propertyValue = AnyConverter.convert(propertyValue, propertyType); } writeMethod.invoke(bean, propertyValue); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, writeMethod); } catch (InvocationTargetException e) { throw ExceptionMapper.configurationException(e, writeMethod); } }
public static Object getFieldValue(Object target, String name, boolean strict) { Class<?> type = target.getClass(); try { Field field = type.getField(name); return getFieldValue(field, target, strict); } catch (NoSuchFieldException e) { if (strict) throw ExceptionMapper.configurationException(e, type.getName() + '.' + name); else { escalator.escalate("Class '" + type + "' does not have a field '" + name + "'", type, name); return null; } } }
@SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T newInstance(Class<T> type, boolean strict, Object... parameters) { if (parameters.length == 0) return newInstanceFromDefaultConstructor(type); Constructor<T> constructorToUse = null; try { Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors(); List<Constructor<T>> candidates = new ArrayList<Constructor<T>>(constructors.length); int paramCount = parameters.length; for (Constructor<T> constructor : constructors) if (constructor.getParameterTypes().length == paramCount) candidates.add(constructor); if (candidates.size() == 1) constructorToUse = candidates.get(0); else if (candidates.size() == 0) throw new ConfigurationError( "No constructor with " + paramCount + " parameters found for " + type); else { // there are several candidates - find the first one with matching types Class<?>[] paramTypes = new Class[parameters.length]; for (int i = 0; i < parameters.length; i++) paramTypes[i] = parameters[i].getClass(); for (Constructor c : type.getConstructors()) { if (typesMatch(c.getParameterTypes(), paramTypes)) { constructorToUse = c; break; } } // there is no ideal match if (constructorToUse == null) { if (strict) throw new NoSuchMethodException( "No appropriate constructor found: " + type + '(' + ArrayFormat.format(", ", paramTypes) + ')'); Exception mostRecentException = null; for (Constructor<T> candidate : candidates) { try { return newInstance(candidate, strict, parameters); } catch (Exception e) { mostRecentException = e; logger.warn("Exception in constructor call: " + candidate, e); continue; // ignore exception and try next constructor } } // no constructor could be called without exception String errMsg = (mostRecentException != null ? "None of these constructors could be called without exception: " + candidates + ", latest exception: " + mostRecentException : type + " has no appropriate constructor for the arguments " + ArrayFormat.format(", ", parameters)); throw new ConfigurationError(errMsg); } } if (!strict) parameters = convertArray(parameters, constructorToUse.getParameterTypes()); return newInstance(constructorToUse, parameters); } catch (SecurityException e) { throw ExceptionMapper.configurationException(e, constructorToUse); } catch (NoSuchMethodException e) { throw ExceptionMapper.configurationException(e, type); } }