List of usage examples for java.lang.reflect Field getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:com.microsoft.windowsazure.mobileservices.MobileServiceTableBase.java
/** * Returns the id property class defined or annotated in the entity class * @param clazz Target entity class/*from w w w. j a v a2 s . c o m*/ * @return Property class */ protected static <F> Class<?> getIdPropertyClass(Class<F> clazz) { // Search for id properties annotations, regardless case for (Field field : clazz.getDeclaredFields()) { SerializedName serializedName = field.getAnnotation(SerializedName.class); if (serializedName != null) { if (IdProperties.contains(serializedName.value())) { return field.getType(); } } else { if (IdProperties.contains(field.getName())) { return field.getType(); } } } return null; }
From source file:cn.teamlab.wg.framework.util.csv.CsvWriter.java
/** * Bean?CSV?//from w w w . ja v a 2 s . com * Bean@CsvPropAnno(index = ?) * @param objList * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static String bean2Csv(List<?> objList) throws Exception { if (objList == null || objList.size() == 0) { return ""; } TreeMap<Integer, CsvFieldBean> map = new TreeMap<Integer, CsvFieldBean>(); Object bean0 = objList.get(0); Class<?> clazz = bean0.getClass(); PropertyDescriptor[] arr = org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor p : arr) { String fieldName = p.getName(); Field field = FieldUtils.getDeclaredField(clazz, fieldName, true); if (field == null) { continue; } boolean isAnno = field.isAnnotationPresent(CsvFieldAnno.class); if (isAnno) { CsvFieldAnno anno = field.getAnnotation(CsvFieldAnno.class); int idx = anno.index(); map.put(idx, new CsvFieldBean(idx, anno.title(), fieldName)); } } // CSVBuffer StringBuffer buff = new StringBuffer(); // ??? boolean withTitle = clazz.isAnnotationPresent(CsvTitleAnno.class); // ??csv if (withTitle) { StringBuffer titleBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); titleBuff.append(Letters.QUOTE).append(fieldBean.getTitle()).append(Letters.QUOTE); titleBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(titleBuff.toString())); buff.append(Letters.LF); titleBuff.setLength(0); } for (Object o : objList) { StringBuffer tmpBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); Object val = BeanUtils.getProperty(o, fieldBean.getFieldName()); if (val != null) { tmpBuff.append(Letters.QUOTE).append(val).append(Letters.QUOTE); } else { tmpBuff.append(StringUtils.EMPTY); } tmpBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(tmpBuff.toString())); buff.append(Letters.LF); tmpBuff.setLength(0); } return buff.toString(); }
From source file:com.evolveum.midpoint.prism.xml.XmlTypeConverter.java
public static <T> String fromXmlEnum(T enumValue) { if (enumValue == null) { return null; }/*from w w w . ja v a 2s . c o m*/ String fieldName = ((Enum) enumValue).name(); Field field; try { field = enumValue.getClass().getField(fieldName); } catch (SecurityException e) { throw new IllegalArgumentException("Error getting field from " + enumValue, e); } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Error getting field from " + enumValue, e); } XmlEnumValue annotation = field.getAnnotation(XmlEnumValue.class); return annotation.value(); }
From source file:com.microsoft.windowsazure.mobileservices.MobileServiceTableBase.java
/** * Returns the system properties defined or annotated in the entity class * @param clazz Target entity class//from w ww . ja v a2s . co m * @return List of entities */ protected static <F> EnumSet<MobileServiceSystemProperty> getSystemProperties(Class<F> clazz) { EnumSet<MobileServiceSystemProperty> result = EnumSet.noneOf(MobileServiceSystemProperty.class); Class<?> idClazz = getIdPropertyClass(clazz); if (idClazz != null && !isIntegerClass(idClazz)) { // Search for system properties annotations, regardless case for (Field field : clazz.getDeclaredFields()) { SerializedName serializedName = field.getAnnotation(SerializedName.class); if (serializedName != null) { if (SystemPropertyNameToEnum.containsKey(serializedName.value())) { result.add(SystemPropertyNameToEnum.get(serializedName.value())); } } else { if (SystemPropertyNameToEnum.containsKey(field.getName())) { result.add(SystemPropertyNameToEnum.get(field.getName())); } } } } // Otherwise, return empty return result; }
From source file:gr.abiss.calipso.uischema.serializer.UiSchemaSerializer.java
private static String getFormFieldConfig(Class domainClass, PropertyDescriptor descriptor, String fieldName) { String formSchemaJson = null; Field field = null; StringBuffer formConfig = new StringBuffer(); String key = domainClass.getName() + "#" + fieldName; String cached = CONFIG_CACHE.get(key); if (StringUtils.isNotBlank(cached)) { formConfig.append(cached);// w w w. j a v a 2 s . c om } else { Class tmpClass = domainClass; do { for (Field tmpField : tmpClass.getDeclaredFields()) { String candidateName = tmpField.getName(); if (candidateName.equals(fieldName)) { field = tmpField; FormSchemas formSchemasAnnotation = null; if (field.isAnnotationPresent(FormSchemas.class)) { formSchemasAnnotation = field.getAnnotation(FormSchemas.class); gr.abiss.calipso.uischema.annotation.FormSchemaEntry[] formSchemas = formSchemasAnnotation .value(); LOGGER.info("getFormFieldConfig, formSchemas: " + formSchemas); if (formSchemas != null) { for (int i = 0; i < formSchemas.length; i++) { if (i > 0) { formConfig.append(comma); } gr.abiss.calipso.uischema.annotation.FormSchemaEntry formSchemaAnnotation = formSchemas[i]; LOGGER.info( "getFormFieldConfig, formSchemaAnnotation: " + formSchemaAnnotation); appendFormFieldSchema(formConfig, formSchemaAnnotation.state(), formSchemaAnnotation.json()); } } //formConfig = formSchemasAnnotation.json(); } else { appendFormFieldSchema(formConfig, gr.abiss.calipso.uischema.annotation.FormSchemaEntry.STATE_DEFAULT, gr.abiss.calipso.uischema.annotation.FormSchemaEntry.TYPE_STRING); } break; } } tmpClass = tmpClass.getSuperclass(); } while (tmpClass != null && field == null); formSchemaJson = formConfig.toString(); CONFIG_CACHE.put(key, formSchemaJson); } return formSchemaJson; }
From source file:com.zlfun.framework.excel.ExcelUtils.java
private static <T> T fill(Map<String, String> map, T t) { T bean = t;/* w ww .j a v a 2s . c om*/ try { if (t.getClass().getAnnotation(WebParam.class) == null) { Field[] fs = t.getClass().getDeclaredFields(); for (Field f : fs) { set(bean, f, map.get(f.getName())); } } else { Field[] fs = t.getClass().getDeclaredFields(); for (Field f : fs) { WebParam param = f.getAnnotation(WebParam.class); if (param != null) { String fname; if ("".equals(param.value())) { fname = f.getName(); } else { fname = param.value(); } set(bean, f, map.get(fname)); } } // ? Class<?> parent = t.getClass().getSuperclass(); while (parent != Object.class) { if (parent.getAnnotation(ItemField.class) != null) { Field[] pfs = parent.getDeclaredFields(); for (Field f : pfs) { WebParam param = f.getAnnotation(WebParam.class); if (param != null) { String fname; if ("".equals(param.value())) { fname = f.getName(); } else { fname = param.value(); } set(bean, f, map.get(fname)); } } parent = parent.getSuperclass(); } else { break; } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return bean; }
From source file:com.github.helenusdriver.driver.impl.DataTypeImpl.java
/** * Infers the data type from the specified field. * * @author paouelle/* w w w. j a v a 2 s.c o m*/ * * @param field the field from which to infer the data type * @return a non-<code>null</code> data type definition * @throws NullPointerException if <code>field</code> is <code>null</code> * @throws IllegalArgumentException if the data type cannot be inferred from * the field or it is persisted but the persister cannot be instantiate */ public static Definition inferDataTypeFrom(Field field) { org.apache.commons.lang3.Validate.notNull(field, "invalid null field"); final Persisted persisted = field.getAnnotation(Persisted.class); if (persisted == null) { final Column.Data cdata = field.getAnnotation(Column.Data.class); if (cdata != null) { final DataType type = cdata.type(); final List<CQLDataType> atypes = new ArrayList<>(Arrays.asList(cdata.arguments())); if (type != DataType.INFERRED) { org.apache.commons.lang3.Validate.isTrue(!(atypes.size() < type.NUM_ARGUMENTS), "missing argument data type(s) for '%s' in field: %s.%s", type.CQL, field.getDeclaringClass().getName(), field.getName()); org.apache.commons.lang3.Validate.isTrue(!((type.NUM_ARGUMENTS == 0) && (atypes.size() != 0)), "data type '%s' is not a collection in field: %s.%s", type.CQL, field.getDeclaringClass().getName(), field.getName()); org.apache.commons.lang3.Validate.isTrue(!(atypes.size() > type.NUM_ARGUMENTS), "too many argument data type(s) for '%s' in field: %s.%s", type.CQL, field.getDeclaringClass().getName(), field.getName()); if (type.NUM_ARGUMENTS != 0) { org.apache.commons.lang3.Validate.isTrue(((DataType) atypes.get(0)).NUM_ARGUMENTS == 0, "collection of collection is not supported in field: %s.%s", field.getDeclaringClass().getName(), field.getName()); org.apache.commons.lang3.Validate.isTrue( !((type.NUM_ARGUMENTS > 1) && (((DataType) atypes.get(1)).NUM_ARGUMENTS != 0)), "collection of collection is not supported in field: %s.%s", field.getDeclaringClass().getName(), field.getName()); if ((((DataType) atypes.get(0)) == DataType.INFERRED) || ((type.NUM_ARGUMENTS > 1) && (((DataType) atypes.get(1)) == DataType.INFERRED))) { // we have an inferred part for the collection so calculate as // if it was all inferred and extract only the part we need final List<CQLDataType> types = new ArrayList<>(3); DataTypeImpl.inferDataTypeFrom(field, field.getType(), types); for (int i = 0; i < atypes.size(); i++) { if (atypes.get(i) == DataType.INFERRED) { atypes.set(i, types.get(i + 1)); // since index 1 corresponds to the collection type } } } } // TODO: should probably check that the CQL specified matches a supported class for it return new Definition(type, atypes); } } } // if we get here then the type was either not inferred or there was no // Column.Data annotation or there was a Persisted annotation final Column.Data cdata = field.getAnnotation(Column.Data.class); if (cdata != null) { // also annotated with @Column.Data // only type supported here is either INFERRED which falls through as if // no data type specified or BLOB final DataType type = cdata.type(); if (type == DataType.BLOB) { return new Definition(DataType.BLOB); } org.apache.commons.lang3.Validate.isTrue(type == DataType.INFERRED, "unsupported data type '%s' in @Persisted annotated field: %s.%s", type.CQL, field.getDeclaringClass().getName(), field.getName()); } final List<CQLDataType> types = new ArrayList<>(3); DataTypeImpl.inferDataTypeFrom(field, field.getType(), types); return new Definition(types); }
From source file:com.mg.framework.utils.MiscUtils.java
/** * ? ? ? ? /*from w w w. j av a 2s . c om*/ * * @param value ? ? * @param locale * @return ? ? * @throws NullPointerException ? <code>value == null</code> */ public static String getEnumTextRepresentation(Enum<?> value, Locale locale) { if (value == null) throw new NullPointerException(); String result; EnumConstantText textAnnot = null; Field fld = ReflectionUtils.findDeclaredField(value.getClass(), value.name()); textAnnot = fld.getAnnotation(EnumConstantText.class); if (textAnnot != null) result = UIUtils.loadL10nText(locale, textAnnot.value()); else result = value.name(); return result; }
From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java
private static void addFields(Class entity, EntityDocModel docModel) { if (entity != null) { Field[] fields = entity.getDeclaredFields(); for (Field field : fields) { //Skip static field if ((Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) == false) { EntityFieldModel fieldModel = new EntityFieldModel(); fieldModel.setName(field.getName()); fieldModel.setType(field.getType().getSimpleName()); fieldModel.setOriginClass(entity.getSimpleName()); fieldModel.setEmbeddedType(ReflectionUtil.isComplexClass(field.getType())); if (ReflectionUtil.isCollectionClass(field.getType())) { DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); }//www.ja va 2s .c o m fieldModel.setGenericType(typeClass); } } APIDescription description = (APIDescription) field.getAnnotation(APIDescription.class); if (description != null) { fieldModel.setDescription(description.value()); } for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType().getName().equals(APIDescription.class.getName()) == false) { EntityConstraintModel entityConstraintModel = new EntityConstraintModel(); entityConstraintModel.setName(annotation.annotationType().getSimpleName()); APIDescription annotationDescription = (APIDescription) annotation.annotationType() .getAnnotation(APIDescription.class); if (annotationDescription != null) { entityConstraintModel.setDescription(annotationDescription.value()); } //rules Object annObj = field.getAnnotation(annotation.annotationType()); if (annObj instanceof NotNull) { entityConstraintModel.setRules("Field is required"); } else if (annObj instanceof PK) { PK pk = (PK) annObj; entityConstraintModel.setRules("<b>Generated:</b> " + pk.generated()); fieldModel.setPrimaryKey(true); } else if (annObj instanceof FK) { FK fk = (FK) annObj; StringBuilder sb = new StringBuilder(); sb.append("<b>Foreign Key:</b> ").append(fk.value().getSimpleName()); sb.append(" (<b>Enforce</b>: ").append(fk.enforce()); sb.append(" <b>Soft reference</b>: ").append(fk.softReference()); if (StringUtils.isNotBlank(fk.referencedField())) { sb.append(" <b>Reference Field</b>: ").append(fk.referencedField()); } sb.append(" )"); entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof ConsumeField) { entityConstraintModel.setRules(""); } else if (annObj instanceof Size) { Size size = (Size) annObj; entityConstraintModel .setRules("<b>Min:</b> " + size.min() + " <b>Max:</b> " + size.max()); } else if (annObj instanceof Pattern) { Pattern pattern = (Pattern) annObj; entityConstraintModel.setRules("<b>Pattern:</b> " + pattern.regexp()); } else if (annObj instanceof Sanitize) { Sanitize sanitize = (Sanitize) annObj; entityConstraintModel .setRules("<b>Sanitize:</b> " + sanitize.value().getSimpleName()); } else if (annObj instanceof Unique) { Unique unique = (Unique) annObj; entityConstraintModel.setRules("<b>Handler:</b> " + unique.value().getSimpleName()); } else if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; StringBuilder sb = new StringBuilder(); if (validValueType.value().length > 0) { sb.append(" <b>Values:</b> ").append(Arrays.toString(validValueType.value())); } if (validValueType.lookupClass().length > 0) { sb.append(" <b>Lookups:</b> "); for (Class lookupClass : validValueType.lookupClass()) { sb.append(lookupClass.getSimpleName()).append(" "); } } if (validValueType.enumClass().length > 0) { sb.append(" <b>Enumerations:</b> "); for (Class enumClass : validValueType.enumClass()) { sb.append(enumClass.getSimpleName()).append(" ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } } entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof Min) { Min min = (Min) annObj; entityConstraintModel.setRules("<b>Min value:</b> " + min.value()); } else if (annObj instanceof Max) { Max max = (Max) annObj; entityConstraintModel.setRules("<b>Max value:</b> " + max.value()); } else if (annObj instanceof Version) { entityConstraintModel.setRules("Entity version; For Multi-Version control"); } else if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); } entityConstraintModel.setRules("<b>Type:</b> " + typeClass); } else { entityConstraintModel.setRules(annotation.toString()); } //Annotations that have related classes if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; entityConstraintModel.getRelatedClasses().add(dataType.value().getSimpleName()); } if (annObj instanceof FK) { FK fk = (FK) annObj; entityConstraintModel.getRelatedClasses().add(fk.value().getSimpleName()); } if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; for (Class lookupClass : validValueType.lookupClass()) { entityConstraintModel.getRelatedClasses().add(lookupClass.getSimpleName()); } StringBuilder sb = new StringBuilder(); for (Class enumClass : validValueType.enumClass()) { sb.append("<br>"); sb.append(enumClass.getSimpleName()).append(": ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } entityConstraintModel .setRules(entityConstraintModel.getRules() + " " + sb.toString()); } fieldModel.getConstraints().add(entityConstraintModel); } } docModel.getFieldModels().add(fieldModel); } } addFields(entity.getSuperclass(), docModel); } }
From source file:org.jongo.marshall.jackson.JacksonIdFieldSelector.java
private boolean hasIdAnnotation(Field f) { Id id = f.getAnnotation(Id.class); MongoId mongoId = f.getAnnotation(MongoId.class); return id != null || mongoId != null; }