List of usage examples for java.lang.reflect Field getType
public Class<?> getType()
From source file:com.google.code.simplestuff.bean.SimpleBean.java
/** * //from w ww. j a v a 2 s .c o m * Returns the hashCode basing considering only the {@link BusinessField} * annotated fields. * * @param bean The bean. * @return The hashCode result. * @throws IllegalArgumentException If the bean is not a Business Object. */ public static int hashCode(Object bean) { if (bean == null) { throw new IllegalArgumentException("The bean passed is null!!!"); } BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext .getBusinessObjectDescriptor(bean.getClass()); // We don't need here a not null check since by contract the // getBusinessObjectDescriptor method always returns an abject. if (businessObjectInfo.getNearestBusinessObjectClass() == null) { return bean.hashCode(); // throw new IllegalArgumentException( // "The bean passed is not annotated in the hierarchy as Business Object!!!"); } Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields(); HashCodeBuilder builder = new HashCodeBuilder(); for (Field field : annotatedField) { field.setAccessible(true); final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class); if ((fieldAnnotation != null) && (fieldAnnotation.includeInHashCode())) { try { // Vincenzo Vitale(vita) May 23, 2007 2:39:26 PM: some // date implementations give not equals values... if ((ClassUtils.isAssignable(field.getType(), Date.class)) || (ClassUtils.isAssignable(field.getType(), Calendar.class))) { Object fieldValue = PropertyUtils.getProperty(bean, field.getName()); if (fieldValue != null) { builder.append(DateUtils.round(fieldValue, Calendar.MILLISECOND)); } } else { builder.append(PropertyUtils.getProperty(bean, field.getName())); } } catch (IllegalAccessException e) { if (log.isDebugEnabled()) { log.debug("IllegalAccessException exception when calculating the hashcode of class" + bean.getClass().toString(), e); } } catch (InvocationTargetException e) { if (log.isDebugEnabled()) { log.debug("InvocationTargetException exception when calculating the hashcode of class" + bean.getClass().toString(), e); } } catch (NoSuchMethodException e) { if (log.isDebugEnabled()) { log.debug("NoSuchMethodException exception when calculating the hashcode of class" + bean.getClass().toString(), e); } } } } return builder.toHashCode(); }
From source file:com.helpinput.utils.Utils.java
public static void setFieldValue(Object target, Field theField, Object value) { if (theField != null) { accessible(theField);/* w w w. j a v a 2 s. c o m*/ try { Object newValue = ConvertUtils.convert(value, theField.getType()); theField.set(target, newValue); } catch (Exception e) { e.printStackTrace(); logger.info(MessageFormat.format("convert error:{0},{1},{2}", target, theField, value)); } } }
From source file:com.jsmartdb.framework.manager.EntityWhere.java
@SuppressWarnings("unchecked") public static void getDefaultWhere(Entity entity, Field[] fields) { for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (EntityHandler.isReserved(field) || EntityHandler.isTransient(field)) { continue; }/*from w w w . j a v a 2 s .c o m*/ if (buildFieldWhere(entity, EntityAlias.getAlias(entity.getClass()), field)) { continue; } if (!EntityContext.isBlockJoin()) { JoinId joinId = EntityHandler.getJoinId(field); if (joinId != null && !EntityContext.getJoinBlockClasses().contains(field.getType())) { if (joinId.join().type() != JoinType.NO_JOIN) { Entity obj = (Entity) EntityHandler.getValue(entity, field); if (obj != null) { String alias = EntityAlias.getAlias(entity.getClass(), field.getType().getName(), field.getName()); buildFieldsWhere(obj, alias, EntityFieldsMapper.getFields(field.getType())); } } continue; } OneToOne oneToOne = EntityHandler.getOneToOne(field); if (oneToOne != null && !EntityContext.getJoinBlockClasses().contains(field.getType())) { if (oneToOne.join().type() != JoinType.NO_JOIN) { Entity obj = (Entity) EntityHandler.getValue(entity, field); if (obj != null) { String alias = EntityAlias.getAlias(entity.getClass(), field.getType().getName(), field.getName()); buildFieldsWhere(obj, alias, EntityFieldsMapper.getFields(field.getType())); } } continue; } OneToMany oneToMany = EntityHandler.getOneToMany(field); if (oneToMany != null) { Class<?> oneToManyClass = EntityHandler.getGenericType(field); if (!EntityContext.getJoinBlockClasses().contains(oneToManyClass)) { if (oneToMany.join().type() != JoinType.NO_JOIN) { if (EntityHandler.getTable(oneToManyClass).type() == TableType.DEFAULT_TABLE) { Collection<Entity> collection = (Collection<Entity>) EntityHandler.getValue(entity, field); if (collection != null && !collection.isEmpty()) { EntityContext.getWhereBuilder().append("("); String alias = EntityAlias.getAlias(entity.getClass(), oneToManyClass.getName(), field.getName()); for (Entity obj : collection) { EntityContext.getWhereBuilder().append("("); buildFieldsWhere(obj, alias, EntityFieldsMapper.getFields(oneToManyClass)); EntityContext.getWhereBuilder() .replace( EntityContext.getWhereBuilder().length() - AND_OPERATOR.length(), EntityContext.getWhereBuilder().length(), "") .append(")" + OR_OPERATOR); } EntityContext.getWhereBuilder() .replace( EntityContext.getWhereBuilder().length() - OR_OPERATOR.length(), EntityContext.getWhereBuilder().length(), "") .append(")" + AND_OPERATOR); } } else { Collection<Entity> collection = (Collection<Entity>) EntityHandler.getValue(entity, field); if (collection != null && !collection.isEmpty()) { EntityContext.getWhereBuilder().append("("); String alias = EntityAlias.getAlias(entity.getClass(), oneToManyClass.getName(), field.getName()); for (Entity obj : collection) { EntityContext.getWhereBuilder().append("("); for (Field fieldy : EntityFieldsMapper.getFields(oneToManyClass)) { JoinId joinIdn = EntityHandler.getJoinId(fieldy); if (buildFieldWhere(obj, alias, fieldy)) { continue; } if (joinIdn != null && fieldy.getType() != entity.getClass()) { Entity joinObj = (Entity) EntityHandler.getValue(obj, fieldy); if (joinObj != null) { EntityContext.getWhereBuilder().append("("); String joinAlias = EntityAlias.getAlias(oneToManyClass, fieldy.getType().getName(), fieldy.getName()); buildFieldsWhere(joinObj, joinAlias, EntityFieldsMapper.getFields(fieldy.getType())); EntityContext.getWhereBuilder() .replace( EntityContext.getWhereBuilder().length() - AND_OPERATOR.length(), EntityContext.getWhereBuilder().length(), "") .append(")" + OR_OPERATOR); } continue; } } EntityContext.getWhereBuilder() .replace( EntityContext.getWhereBuilder().length() - AND_OPERATOR.length(), EntityContext.getWhereBuilder().length(), "") .append(")" + OR_OPERATOR); } EntityContext.getWhereBuilder() .replace( EntityContext.getWhereBuilder().length() - OR_OPERATOR.length(), EntityContext.getWhereBuilder().length(), "") .append(")" + AND_OPERATOR); } } } continue; } } ManyToMany manyToMany = EntityHandler.getManyToMany(field); if (manyToMany != null) { Class<?> manyToManyClass = EntityHandler.getGenericType(field); if (!EntityContext.getJoinBlockClasses().contains(manyToManyClass)) { if (manyToMany.join().type() != JoinType.NO_JOIN) { Collection<Entity> collection = (Collection<Entity>) EntityHandler.getValue(entity, field); if (collection != null && !collection.isEmpty()) { EntityContext.getWhereBuilder().append("("); String alias = EntityAlias.getAlias(entity.getClass(), manyToManyClass.getName(), field.getName()); for (Entity obj : collection) { EntityContext.getWhereBuilder().append("("); buildFieldsWhere(obj, alias, EntityFieldsMapper.getFields(manyToManyClass)); EntityContext.getWhereBuilder().replace( EntityContext.getWhereBuilder().length() - AND_OPERATOR.length(), EntityContext.getWhereBuilder().length(), "").append(")" + OR_OPERATOR); } EntityContext.getWhereBuilder() .replace(EntityContext.getWhereBuilder().length() - OR_OPERATOR.length(), EntityContext.getWhereBuilder().length(), "") .append(")" + AND_OPERATOR); } } continue; } } } } if (EntityContext.getWhereBuilder().length() > WHERE_STATEMENT.length()) { EntityContext.getWhereBuilder().replace( EntityContext.getWhereBuilder().length() - AND_OPERATOR.length(), EntityContext.getWhereBuilder().length(), ""); } else { EntityContext.getWhereBuilder().replace( EntityContext.getWhereBuilder().length() - WHERE_STATEMENT.length(), EntityContext.getWhereBuilder().length(), ""); } }
From source file:fr.ign.cogit.geoxygene.datatools.ojb.GeOxygeneBrokerHelper.java
public static String buildMessageString(Object obj, Object value, Field field) { String eol = SystemUtils.LINE_SEPARATOR; StringBuffer buf = new StringBuffer(); buf.append(eol + "object class[ " //$NON-NLS-1$ + (obj != null ? obj.getClass().getName() : null)).append(eol + "target field: " //$NON-NLS-1$ + (field != null ? field.getName() : null)) .append(eol + "target field type: " //$NON-NLS-1$ + (field != null ? field.getType() : null)) .append(eol + "object value class: " //$NON-NLS-1$ + (value != null ? value.getClass().getName() : null)) .append(eol + "object value: " //$NON-NLS-1$ + (value != null ? value : null)) .append("]"); //$NON-NLS-1$ return buf.toString(); }
From source file:com.zlfun.framework.excel.ExcelUtils.java
private static void set(Object obj, Field field, String value) { if (value == null) { return;/* w ww .ja va 2s . c o m*/ } try { if (!field.isAccessible()) { field.setAccessible(true); } Object val = value; if (field.getType() == int.class) { try { val = Integer.parseInt(value); } catch (Exception ex) { val = -1; } } else if (field.getType() == long.class) { try { val = Long.parseLong(value); } catch (Exception ex) { val = -1l; } } else if (field.getType() == double.class) { val = Double.parseDouble(value); } else if (field.getType() == byte.class) { val = Byte.parseByte(value); } else if (field.getType() == boolean.class) { val = Boolean.parseBoolean(value); } field.set(obj, val); } catch (Exception e) { } }
From source file:com.helpinput.core.Utils.java
public static void setFieldValue(Object target, Field theField, Object value) { if (theField != null) { setAccess(theField);/*from w w w.ja va 2s . c om*/ try { Object newValue = ConvertUtils.convert(value, theField.getType()); theField.set(target, newValue); } catch (Exception e) { e.printStackTrace(); logger.info(MessageFormat.format("convert error:{0},{1},{2}", target, theField, value)); } } }
From source file:com.espertech.esper.util.PopulateUtil.java
public static void populateObject(String operatorName, int operatorNum, String dataFlowName, Map<String, Object> objectProperties, Object top, EngineImportService engineImportService, EPDataFlowOperatorParameterProvider optionalParameterProvider, Map<String, Object> optionalParameterURIs) throws ExprValidationException { Class applicableClass = top.getClass(); Set<WriteablePropertyDescriptor> writables = PropertyHelper.getWritableProperties(applicableClass); Set<Field> annotatedFields = JavaClassHelper.findAnnotatedFields(top.getClass(), DataFlowOpParameter.class); Set<Method> annotatedMethods = JavaClassHelper.findAnnotatedMethods(top.getClass(), DataFlowOpParameter.class); // find catch-all methods Set<Method> catchAllMethods = new LinkedHashSet<Method>(); if (annotatedMethods != null) { for (Method method : annotatedMethods) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0); if (anno.all()) { if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class && method.getParameterTypes()[1] == Object.class) { catchAllMethods.add(method); continue; }/*from w w w.j av a 2 s . c o m*/ throw new ExprValidationException("Invalid annotation for catch-call"); } } } // map provided values for (Map.Entry<String, Object> property : objectProperties.entrySet()) { boolean found = false; String propertyName = property.getKey(); // invoke catch-all setters for (Method method : catchAllMethods) { try { method.invoke(top, new Object[] { propertyName, property.getValue() }); } catch (IllegalAccessException e) { throw new ExprValidationException("Illegal access invoking method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + method.getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException("Exception invoking method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + method.getName() + ": " + e.getTargetException().getMessage(), e); } found = true; } if (propertyName.toLowerCase().equals(CLASS_PROPERTY_NAME)) { continue; } // use the writeable property descriptor (appropriate setter method) from writing the property WriteablePropertyDescriptor descriptor = findDescriptor(applicableClass, propertyName, writables); if (descriptor != null) { Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(), descriptor.getType(), engineImportService, false); try { descriptor.getWriteMethod().invoke(top, new Object[] { coerceProperty }); } catch (IllegalArgumentException e) { throw new ExprValidationException("Illegal argument invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName() + " provided value " + coerceProperty, e); } catch (IllegalAccessException e) { throw new ExprValidationException("Illegal access invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException("Exception invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName() + ": " + e.getTargetException().getMessage(), e); } continue; } // find the field annotated with {@link @GraphOpProperty} for (Field annotatedField : annotatedFields) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, annotatedField.getDeclaredAnnotations()).get(0); if (anno.name().equals(propertyName) || annotatedField.getName().equals(propertyName)) { Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(), annotatedField.getType(), engineImportService, true); try { annotatedField.setAccessible(true); annotatedField.set(top, coerceProperty); } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } found = true; break; } } if (found) { continue; } throw new ExprValidationException("Failed to find writable property '" + propertyName + "' for class " + applicableClass.getName()); } // second pass: if a parameter URI - value pairs were provided, check that if (optionalParameterURIs != null) { for (Field annotatedField : annotatedFields) { try { annotatedField.setAccessible(true); String uri = operatorName + "/" + annotatedField.getName(); if (optionalParameterURIs.containsKey(uri)) { Object value = optionalParameterURIs.get(uri); annotatedField.set(top, value); if (log.isDebugEnabled()) { log.debug("Found parameter '" + uri + "' for data flow " + dataFlowName + " setting " + value); } } else { if (log.isDebugEnabled()) { log.debug("Not found parameter '" + uri + "' for data flow " + dataFlowName); } } } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } } for (Method method : annotatedMethods) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0); if (anno.all()) { if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class && method.getParameterTypes()[1] == Object.class) { for (Map.Entry<String, Object> entry : optionalParameterURIs.entrySet()) { String[] elements = URIUtil.parsePathElements(URI.create(entry.getKey())); if (elements.length < 2) { throw new ExprValidationException("Failed to parse URI '" + entry.getKey() + "', expected " + "'operator_name/property_name' format"); } if (elements[0].equals(operatorName)) { try { method.invoke(top, new Object[] { elements[1], entry.getValue() }); } catch (IllegalAccessException e) { throw new ExprValidationException( "Illegal access invoking method for property '" + entry.getKey() + "' for class " + applicableClass.getName() + " method " + method.getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException( "Exception invoking method for property '" + entry.getKey() + "' for class " + applicableClass.getName() + " method " + method.getName() + ": " + e.getTargetException().getMessage(), e); } } } } } } } // third pass: if a parameter provider is provided, use that if (optionalParameterProvider != null) { for (Field annotatedField : annotatedFields) { try { annotatedField.setAccessible(true); Object provided = annotatedField.get(top); Object value = optionalParameterProvider.provide(new EPDataFlowOperatorParameterProviderContext( operatorName, annotatedField.getName(), top, operatorNum, provided, dataFlowName)); if (value != null) { annotatedField.set(top, value); } } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } } } }
From source file:com.plusub.lib.annotate.JsonParserUtils.java
/** * //from ww w . j a v a 2s. c om * <p>Title: setFieldValue * <p>Description: * @param object * @param field * @param value */ private static void setFieldValue(Object object, Field field, Object value) { Object ov = null; try { ov = getType(field, value, field.getName()); field.set(object, ov); } catch (IllegalAccessException e) { // TODO Auto-generated catch block if (showLog) { e.printStackTrace(); } //fieldset try { Method m = object.getClass().getMethod(getSetMethodName(field), field.getType()); if (m != null) { m.invoke(object, ov); } } catch (Exception e1) { // TODO Auto-generated catch block if (showLog) { Logger.e(TAG, "set field value fail field:" + field.getName() + " method:" + getSetMethodName(field)); e1.printStackTrace(); } } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block if (showLog) { e.printStackTrace(); } } catch (Exception e) { if (showLog) { e.printStackTrace(); } } }
From source file:com.sm.query.utils.QueryUtils.java
/** * @param object/*from www. j a va 2 s. c o m*/ * @param metaData - hashmap of ClassInfo * @return ClassInfo which represent * use getSimpleName() instead of getName() */ public static ClassInfo findClassInfo(Object object, Map<String, ClassInfo> metaData) { String className = object.getClass().getName(); //getSimpleName without package name space String keyName = object.getClass().getSimpleName(); ClassInfo info = metaData.get(keyName); if (info == null) { Type type = getType(className); Object obj; Collection values; switch (type) { case ARRAY: obj = Array.get(object, 0); //info = findClassInfo(object, cacheMetaData); assert (obj != null); info = findClassInfo(obj, metaData); break; case MAP: values = ((Map) object).values(); obj = values.iterator().next(); assert (obj != null); info = findClassInfo(obj, metaData); break; case HASHSET: case LIST: Iterator v = ((Collection) object).iterator(); obj = v.next(); info = findClassInfo(obj, metaData); break; case OBJECT: List<FieldInfo> list = new ArrayList<FieldInfo>(); Class<?> cls = object.getClass(); while (cls != null && cls != Object.class) { Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { if (!isSkipField(field)) { field.setAccessible(true); String fieldClsName = field.getType().getName(); Type fieldType = getType(fieldClsName); list.add(new FieldInfo(field, fieldType, fieldClsName)); } } cls = cls.getSuperclass(); } if (list.size() > 0) { FieldInfo[] fieldArray = new FieldInfo[list.size()]; fieldArray = list.toArray(fieldArray); info = new ClassInfo(className, type, fieldArray); } break; default: logger.error("Wrong type =" + type + " in createClassInfo object className " + className + " simple name " + keyName); } // switch metaData.put(keyName, info); } return info; }
From source file:net.ceos.project.poi.annotated.core.CellHandler.java
protected static boolean isAuthorizedType(Field field) { return Arrays.asList(array).contains(field.getType().getName()) || field.getType().isEnum(); }