List of usage examples for java.lang.reflect Field getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static Set<String> mapValueField(List<APIValueFieldModel> fieldModels, Field fields[], boolean onlyComsumeField) { Set<String> fieldNamesCaptured = new HashSet<>(); for (Field field : fields) { boolean capture = true; if (onlyComsumeField) { ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class); if (consumeField == null) { capture = false;// w w w. j a v a 2 s.co m } } if (capture) { APIValueFieldModel fieldModel = new APIValueFieldModel(); fieldModel.setFieldName(field.getName()); fieldNamesCaptured.add(field.getName()); fieldModel.setType(field.getType().getSimpleName()); DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } fieldModel.setType(fieldModel.getType() + ": " + typeName); } NotNull requiredParam = (NotNull) field.getAnnotation(NotNull.class); if (requiredParam != null) { fieldModel.setRequired(true); } StringBuilder validation = new StringBuilder(); ParamTypeDescription description = (ParamTypeDescription) field .getAnnotation(ParamTypeDescription.class); if (description != null) { validation.append(description.value()).append("<br>"); } APIDescription aPIDescription = (APIDescription) field.getAnnotation(APIDescription.class); if (aPIDescription != null) { fieldModel.setDescription(aPIDescription.value()); } if ("Date".equals(field.getType().getSimpleName())) { validation.append("Timestamp (milliseconds since UNIX Epoch<br>"); } if ("boolean".equalsIgnoreCase(field.getType().getSimpleName())) { validation.append("T | F"); } ValidationRequirement validationRequirement = (ValidationRequirement) field .getAnnotation(ValidationRequirement.class); if (validationRequirement != null) { validation.append(validationRequirement.value()).append("<br>"); } PK pk = (PK) field.getAnnotation(PK.class); if (pk != null) { if (pk.generated()) { validation.append("Primary Key (Generated)").append("<br>"); } else { validation.append("Primary Key").append("<br>"); } } Min min = (Min) field.getAnnotation(Min.class); if (min != null) { validation.append("Min Value: ").append(min.value()).append("<br>"); } Max max = (Max) field.getAnnotation(Max.class); if (max != null) { validation.append("Max Value: ").append(max.value()).append("<br>"); } Size size = (Size) field.getAnnotation(Size.class); if (size != null) { validation.append("Min Length: ").append(size.min()).append(" Max Length: ").append(size.max()) .append("<br>"); } Pattern pattern = (Pattern) field.getAnnotation(Pattern.class); if (pattern != null) { validation.append("Needs to Match: ").append(pattern.regexp()).append("<br>"); } ValidValueType validValueType = (ValidValueType) field.getAnnotation(ValidValueType.class); if (validValueType != null) { validation.append("Set of valid values: ").append(Arrays.toString(validValueType.value())) .append("<br>"); if (validValueType.lookupClass().length > 0) { validation.append("See Lookup table(s): <br>"); for (Class lookupClass : validValueType.lookupClass()) { validation.append(lookupClass.getSimpleName()); } } if (validValueType.enumClass().length > 0) { validation.append("See Enum List: <br>"); for (Class enumClass : validValueType.enumClass()) { validation.append(enumClass.getSimpleName()); if (enumClass.isEnum()) { validation.append(" (").append(Arrays.toString(enumClass.getEnumConstants())) .append(") "); } } } } fieldModel.setValidation(validation.toString()); fieldModels.add(fieldModel); } } return fieldNamesCaptured; }
From source file:com.github.helenusdriver.driver.impl.DataTypeImpl.java
/** * Infers the data type for the specified field. * * @author paouelle/*from ww w . j a v a 2 s. co m*/ * * @param field the non-<code>null</code> field to infer the CQL data type for * @param clazz the non-<code>null</code> class for which to infer the CQL * data type for the field * @param types the non-<code>null</code> list where to add the inferred type and * its arguments * @throws IllegalArgumentException if the data type cannot be inferred from * the field */ private static void inferDataTypeFrom(Field field, Class<?> clazz, List<CQLDataType> types) { inferDataTypeFrom(field, clazz, types, field.getAnnotation(Persisted.class)); }
From source file:com.madrobot.di.Converter.java
public static void storeValue(final JSONObject jsonObject, final String key, Object value, final Field field) throws JSONException { Class<?> classType = field.getType(); if (clzTypeKeyMap.containsKey(classType)) { final int code = clzTypeKeyMap.get(classType); switch (code) { case TYPE_STRING: case TYPE_SHORT: case TYPE_INT: case TYPE_LONG: case TYPE_CHAR: case TYPE_FLOAT: case TYPE_DOUBLE: break; case TYPE_BOOLEAN: Boolean userValue = (Boolean) value; if (field.isAnnotationPresent(BooleanFormat.class)) { BooleanFormat formatAnnotation = field.getAnnotation(BooleanFormat.class); String trueFormat = formatAnnotation.trueFormat(); String falseFormat = formatAnnotation.falseFormat(); if (userValue) { value = trueFormat;// w ww . j ava 2 s . c o m } else { value = falseFormat; } } else { value = userValue; } break; case TYPE_DATE: Date date = (Date) value; SimpleDateFormat simpleDateFormat = null; if (field.isAnnotationPresent(com.madrobot.di.wizard.json.annotations.DateFormat.class)) { com.madrobot.di.wizard.json.annotations.DateFormat formatAnnotation = field .getAnnotation(com.madrobot.di.wizard.json.annotations.DateFormat.class); String dateFormat = formatAnnotation.format(); simpleDateFormat = new SimpleDateFormat(dateFormat); } else { simpleDateFormat = new SimpleDateFormat(); } value = simpleDateFormat.format(date); break; } jsonObject.put(key, value); } }
From source file:gr.abiss.calipso.jpasearch.json.serializer.FormSchemaSerializer.java
private static String getFormFieldConfig(Class domainClass, 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 ww .jav a 2 s . co m*/ } 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.jpasearch.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.jpasearch.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.jpasearch.annotation.FormSchemaEntry.STATE_DEFAULT, gr.abiss.calipso.jpasearch.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.feilong.core.bean.BeanUtil.java
/** * ??? klass {@link Alias} , ?? {@link Alias#name()} ?map . * * @param klass// w w w . ja v a 2 s.c om * the klass * @return <code>klass</code> {@link Alias} , {@link Collections#emptyMap()} * @throws NullPointerException * <code>klass</code> null * @since 1.8.1 */ private static Map<String, String> buildPropertyNameAndAliasMap(Class<?> klass) { Validate.notNull(klass, "klass can't be null!"); List<Field> aliasFieldsList = FieldUtils.getFieldsListWithAnnotation(klass, Alias.class); if (isNullOrEmpty(aliasFieldsList)) { return emptyMap(); } //??key Map<String, String> propertyNameAndAliasMap = newHashMap(aliasFieldsList.size()); for (Field field : aliasFieldsList) { Alias alias = field.getAnnotation(Alias.class); propertyNameAndAliasMap.put(field.getName(), alias.name()); } return propertyNameAndAliasMap; }
From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java
/** * ?/*from w ww.j ava2 s .co m*/ * @param request */ @SuppressWarnings("unchecked") public static org.apache.http.Header[] parseRequestHeaders(Request request) { List<org.apache.http.Header> finalHeaders = null; for (Field field : getFields(request.getClass(), true, true, true)) { field.setAccessible(true); if (field.getAnnotation(Header.class) != null) { //??? try { Object value = field.get(request); if (value != null) { if (org.apache.http.Header.class.isAssignableFrom(field.getType())) { //? if (finalHeaders == null) { finalHeaders = new LinkedList<org.apache.http.Header>(); } finalHeaders.add((org.apache.http.Header) value); } else if (isArrayByType(field, org.apache.http.Header.class)) { //Header org.apache.http.Header[] headers = (org.apache.http.Header[]) value; for (org.apache.http.Header header : headers) { if (header != null) { if (finalHeaders == null) { finalHeaders = new LinkedList<org.apache.http.Header>(); } finalHeaders.add(header); } } } else if (isCollectionByType(field, Collection.class, org.apache.http.Header.class)) { //Header? if (finalHeaders == null) { finalHeaders = new LinkedList<org.apache.http.Header>(); } finalHeaders.addAll((Collection<org.apache.http.Header>) value); } } } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (IllegalArgumentException e1) { e1.printStackTrace(); } } } if (finalHeaders != null && finalHeaders.size() > 0) { org.apache.http.Header[] heades = new org.apache.http.Header[finalHeaders.size()]; finalHeaders.toArray(heades); return heades; } else { return null; } }
From source file:net.minecraftforge.common.config.ConfigManager.java
private static void sync(Configuration cfg, Class<?> cls, String modid, String category, boolean loading, Object instance) {//ww w . j av a 2 s .c o m for (Field f : cls.getDeclaredFields()) { if (!Modifier.isPublic(f.getModifiers())) continue; //Only the root class may have static fields. Otherwise category tree nodes of the same type would share the //contained value messing up the sync if (Modifier.isStatic(f.getModifiers()) != (instance == null)) continue; if (f.isAnnotationPresent(Config.Ignore.class)) continue; String comment = null; Comment ca = f.getAnnotation(Comment.class); if (ca != null) comment = NEW_LINE.join(ca.value()); String langKey = modid + "." + (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER) + f.getName().toLowerCase(Locale.ENGLISH); LangKey la = f.getAnnotation(LangKey.class); if (la != null) langKey = la.value(); boolean requiresMcRestart = f.isAnnotationPresent(Config.RequiresMcRestart.class); boolean requiresWorldRestart = f.isAnnotationPresent(Config.RequiresWorldRestart.class); if (FieldWrapper.hasWrapperFor(f)) //Wrappers exist for primitives, enums, maps and arrays { if (Strings.isNullOrEmpty(category)) throw new RuntimeException( "An empty category may not contain anything but objects representing categories!"); try { IFieldWrapper wrapper = FieldWrapper.get(instance, f, category); ITypeAdapter adapt = wrapper.getTypeAdapter(); Property.Type propType = adapt.getType(); for (String key : wrapper.getKeys()) //Iterate the fully qualified property names the field provides { String suffix = StringUtils.replaceOnce(key, wrapper.getCategory() + Configuration.CATEGORY_SPLITTER, ""); boolean existed = exists(cfg, wrapper.getCategory(), suffix); if (!existed || loading) //Creates keys in category specified by the wrapper if new ones are programaticaly added { Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter()); adapt.setDefaultValue(property, wrapper.getValue(key)); if (!existed) adapt.setValue(property, wrapper.getValue(key)); else wrapper.setValue(key, adapt.getValue(property)); } else //If the key is not new, sync according to shouldReadFromVar() { Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter()); Object propVal = adapt.getValue(property); Object mapVal = wrapper.getValue(key); if (shouldReadFromVar(property, propVal, mapVal)) adapt.setValue(property, mapVal); else wrapper.setValue(key, propVal); } } ConfigCategory confCat = cfg.getCategory(wrapper.getCategory()); for (Property property : confCat.getOrderedValues()) //Iterate the properties to check for new data from the config side { String key = confCat.getQualifiedName() + Configuration.CATEGORY_SPLITTER + property.getName(); if (!wrapper.handlesKey(key)) continue; if (loading || !wrapper.hasKey(key)) { Object value = wrapper.getTypeAdapter().getValue(property); wrapper.setValue(key, value); } } if (loading) wrapper.setupConfiguration(cfg, comment, langKey, requiresMcRestart, requiresWorldRestart); } catch (Exception e) { String format = "Error syncing field '%s' of class '%s'!"; String error = String.format(format, f.getName(), cls.getName()); throw new RuntimeException(error, e); } } else if (f.getType().getSuperclass() != null && f.getType().getSuperclass().equals(Object.class)) { //If the field extends Object directly, descend the object tree and access the objects members Object newInstance = null; try { newInstance = f.get(instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } //Setup the sub category with its respective name, comment, language key, etc. String sub = (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER) + getName(f).toLowerCase(Locale.ENGLISH); ConfigCategory confCat = cfg.getCategory(sub); confCat.setComment(comment); confCat.setLanguageKey(langKey); confCat.setRequiresMcRestart(requiresMcRestart); confCat.setRequiresWorldRestart(requiresWorldRestart); sync(cfg, f.getType(), modid, sub, loading, newInstance); } else { String format = "Can't handle field '%s' of class '%s': Unknown type."; String error = String.format(format, f.getName(), cls.getCanonicalName()); throw new RuntimeException(error); } } }
From source file:com.unboundid.scim2.common.utils.SchemaUtils.java
/** * Gets SCIM schema attributes for a class. * * @param classesProcessed a stack containing the classes processed prior * to this class. This is used for cycle detection. * @param cls the class to get the attributes for. * @return a collection of SCIM schema attributes for the class. * @throws IntrospectionException thrown if an error occurs during * Introspection.//w w w .ja v a 2s. c om */ private static Collection<AttributeDefinition> getAttributes(final Stack<String> classesProcessed, final Class<?> cls) throws IntrospectionException { String className = cls.getCanonicalName(); if (!cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { throw new RuntimeException("Cycles detected in Schema"); } Collection<PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(cls); Collection<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals("subAttributes") && cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { // Skip second nesting of subAttributes the second time around // since there is no subAttributes of subAttributes in SCIM. continue; } AttributeDefinition.Builder attributeBuilder = new AttributeDefinition.Builder(); Field field = findField(cls, propertyDescriptor.getName()); if (field == null) { continue; } Attribute schemaProperty = null; JsonProperty jsonProperty = null; if (field.isAnnotationPresent(Attribute.class)) { schemaProperty = field.getAnnotation(Attribute.class); } if (field.isAnnotationPresent(JsonProperty.class)) { jsonProperty = field.getAnnotation(JsonProperty.class); } // Only generate schema for annotated fields. if (schemaProperty == null) { continue; } addName(attributeBuilder, propertyDescriptor, jsonProperty); addDescription(attributeBuilder, schemaProperty); addCaseExact(attributeBuilder, schemaProperty); addRequired(attributeBuilder, schemaProperty); addReturned(attributeBuilder, schemaProperty); addUniqueness(attributeBuilder, schemaProperty); addReferenceTypes(attributeBuilder, schemaProperty); addMutability(attributeBuilder, schemaProperty); addMultiValued(attributeBuilder, propertyDescriptor, schemaProperty); addCanonicalValues(attributeBuilder, schemaProperty); Class propertyCls = propertyDescriptor.getPropertyType(); // if this is a multivalued attribute the real sub attribute class is the // the one specified in the annotation, not the list, set, array, etc. if ((schemaProperty.multiValueClass() != NullType.class)) { propertyCls = schemaProperty.multiValueClass(); } AttributeDefinition.Type type = getAttributeType(propertyCls); attributeBuilder.setType(type); if (type == AttributeDefinition.Type.COMPLEX) { // Add this class to the list to allow cycle detection classesProcessed.push(cls.getCanonicalName()); Collection<AttributeDefinition> subAttributes = getAttributes(classesProcessed, propertyCls); attributeBuilder .addSubAttributes(subAttributes.toArray(new AttributeDefinition[subAttributes.size()])); classesProcessed.pop(); } attributes.add(attributeBuilder.build()); } return attributes; }
From source file:cn.org.awcp.core.mybatis.mapper.EntityHelper.java
/** * ?//from w w w . jav a2 s . co m * * @param entityClass */ public static synchronized void initEntityNameMap(Class<?> entityClass) { if (entityTableMap.get(entityClass) != null) { return; } // ?? EntityTable entityTable = null; if (entityClass.isAnnotationPresent(Table.class)) { Table table = entityClass.getAnnotation(Table.class); if (!table.name().equals("")) { entityTable = new EntityTable(); entityTable.setTable(table); } } if (entityTable == null) { entityTable = new EntityTable(); entityTable.name = camelhumpToUnderline(entityClass.getSimpleName()).toUpperCase(); } entityTableMap.put(entityClass, entityTable); // List<Field> fieldList = getAllField(entityClass, null); List<EntityColumn> columnList = new ArrayList<EntityColumn>(); List<EntityColumn> pkColumnList = new ArrayList<EntityColumn>(); List<EntityColumn> obColumnList = new ArrayList<EntityColumn>(); for (Field field : fieldList) { // if (field.isAnnotationPresent(Transient.class)) { continue; } EntityColumn entityColumn = new EntityColumn(); if (field.isAnnotationPresent(Id.class)) { entityColumn.setId(true); } if (field.isAnnotationPresent(OrderBy.class)) { OrderBy orderBy = field.getAnnotation(OrderBy.class); if (StringUtils.isNotBlank(orderBy.value()) && orderBy.value().equalsIgnoreCase("desc")) { entityColumn.setOrderBy(OrderByEnum.DESC); } else { entityColumn.setOrderBy(OrderByEnum.ASC); } } String columnName = null; if (field.isAnnotationPresent(Column.class)) { Column column = field.getAnnotation(Column.class); columnName = column.name(); } if (columnName == null || columnName.equals("")) { columnName = camelhumpToUnderline(field.getName()); } entityColumn.setProperty(field.getName()); entityColumn.setColumn(columnName.toUpperCase()); entityColumn.setJavaType(field.getType()); // - Oracle?MySqlUUID if (field.isAnnotationPresent(SequenceGenerator.class)) { SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class); if (sequenceGenerator.sequenceName().equals("")) { throw new RuntimeException(entityClass + "" + field.getName() + "@SequenceGeneratorsequenceName!"); } entityColumn.setSequenceName(sequenceGenerator.sequenceName()); } else if (field.isAnnotationPresent(GeneratedValue.class)) { GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class); if (generatedValue.generator().equals("UUID")) { if (field.getType().equals(String.class)) { entityColumn.setUuid(true); } else { throw new RuntimeException(field.getName() + " - @GeneratedValue?UUID?String"); } } else if (generatedValue.generator().equals("JDBC")) { if (Number.class.isAssignableFrom(field.getType())) { entityColumn.setIdentity(true); entityColumn.setGenerator("JDBC"); } else { throw new RuntimeException(field.getName() + " - @GeneratedValue?UUID?String"); } } else { // ?generator??idsql,mysql=CALL // IDENTITY(),hsqldb=SELECT SCOPE_IDENTITY() // ??generator if (generatedValue.strategy() == GenerationType.IDENTITY) { // mysql entityColumn.setIdentity(true); if (!generatedValue.generator().equals("")) { String generator = null; MapperHelper.IdentityDialect identityDialect = MapperHelper.IdentityDialect .getDatabaseDialect(generatedValue.generator()); if (identityDialect != null) { generator = identityDialect.getIdentityRetrievalStatement(); } else { generator = generatedValue.generator(); } entityColumn.setGenerator(generator); } } else { throw new RuntimeException(field.getName() + " - @GeneratedValue?????:" + "\n1.?@GeneratedValue(generator=\"UUID\")" + "\n2.useGeneratedKeys@GeneratedValue(generator=\\\"JDBC\\\") " + "\n3.mysql?@GeneratedValue(strategy=GenerationType.IDENTITY[,generator=\"Mysql\"])"); } } } columnList.add(entityColumn); if (entityColumn.isId()) { pkColumnList.add(entityColumn); } if (entityColumn.getOrderBy() != null) { obColumnList.add(entityColumn); } } if (pkColumnList.size() == 0) { pkColumnList = columnList; } entityClassColumns.put(entityClass, columnList); entityClassPKColumns.put(entityClass, pkColumnList); entityOrderByColumns.put(entityClass, obColumnList); }
From source file:com.seer.datacruncher.utils.generic.CommonUtils.java
/** * Method recursively iterate all fields * @throws IllegalAccessException// w w w . ja va2s . c o m * @throws IllegalArgumentException */ private static void recursiveIterateObjectWithXPath(Object obj, String strXPath, List<String> xPath, int location, Map<String, String> map) throws IllegalArgumentException, IllegalAccessException { if (obj == null) return; if (location > xPath.size()) return; Field fields[] = obj.getClass().getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); String xmlElement = null; String xmlElementRef = null; String xmlAttribute = null; if (f.isAnnotationPresent(XmlElement.class)) { xmlElement = f.getAnnotation(XmlElement.class).name(); } else if (f.isAnnotationPresent(XmlElementRef.class)) { xmlAttribute = f.getAnnotation(XmlElementRef.class).name(); } else if (f.isAnnotationPresent(XmlAttribute.class)) { xmlAttribute = f.getAnnotation(XmlAttribute.class).name(); } if (xPath.get(location).equals(xmlElement) || xPath.get(location).equals(f.getName()) || xPath.get(location).equals(xmlElementRef) || xPath.get(location).equals(xmlAttribute)) { Object fieldObject = f.get(obj); if (location + 1 == xPath.size()) { if (fieldObject instanceof JAXBElement) { map.put(strXPath, "" + ((JAXBElement<?>) fieldObject).getValue()); } else { if (fieldObject != null) map.put(strXPath, fieldObject.toString()); } return; } else { if (f.get(obj) instanceof List) { for (Object o : (List<?>) f.get(obj)) { recursiveIterateObjectWithXPath(o, strXPath, xPath, location + 1, map); } } else { recursiveIterateObjectWithXPath(f.get(obj), strXPath, xPath, location + 1, map); } } } } }