Java Code Examples for java.lang.reflect.Field.getAnnotation()

The following are Jave code examples for showing how to use getAnnotation() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: saluki   File: ProtobufSerializerUtils.java   View Source Code Vote up 6 votes
public static final Map<Field, ProtobufAttribute> getAllProtbufFields(
    Class<? extends Object> fromClazz) {
  Map<Field, ProtobufAttribute> protoBufFields =
      CLASS_TO_FIELD_MAP_CACHE.get(fromClazz.getCanonicalName());
  if (protoBufFields != null) {
    return protoBufFields;
  } else {
    protoBufFields = new HashMap<>();
  }
  final List<Field> fields = JReflectionUtils.getAllFields(new ArrayList<Field>(), fromClazz);
  for (Field field : fields) {
    final Annotation annotation = field.getAnnotation(ProtobufAttribute.class);
    if (annotation == null) {
      continue;
    }
    final ProtobufAttribute gpbAnnotation = (ProtobufAttribute) annotation;
    protoBufFields.put(field, gpbAnnotation);
  }
  CLASS_TO_FIELD_MAP_CACHE.put(fromClazz.getCanonicalName(), protoBufFields);
  return protoBufFields;
}
 
Example 2
Project: hibatis   File: CollectionProperty.java   View Source Code Vote up 6 votes
public CollectionProperty(EntityMetadata metadata, Field field) {
	super(metadata, field);
	Collection collection = field.getAnnotation(Collection.class);
	if(!java.util.Collection.class.isAssignableFrom(field.getType())){
		throw new HibatisException("Collection属性必须为集合类型");
	}
	this.isLazy = collection.lazy();
	this.isIn = collection.in();
	this.cacheable = collection.cacheable();
	ParameterizedType type = (ParameterizedType) field.getGenericType();
	this.referenceType = (Class<?>) type.getActualTypeArguments()[0];
	this.rawType = field.getType();
	if(this.rawType != List.class){
		throw new HibatisException("@Collection只支持java.util.List类型");
	}
	this.setProperties(collection.property());
	this.setReferences(collection.reference());
	String[] orderBy = collection.orderBy();
	if(orderBy != null){
		sorts = new Sort[orderBy.length];
		for (int i = 0; i < sorts.length; i++) {
			String order = orderBy[i];
			sorts[i] = Sort.parse(order);
		}
	}
}
 
Example 3
Project: vind   File: DefaultIdGenerator.java   View Source Code Vote up 5 votes
@Override
public String compose(String fieldValue, Field idField, Class<?> clazz) {
    final Id id = idField.getAnnotation(Id.class);
    if (id == null) {
        throw new IllegalArgumentException("Missing Id-annotation on Id-annotated field? Weird...");
    } else {
        return id.prefix() + fieldValue + id.suffix();
    }
}
 
Example 4
Project: OftenPorter   File: DataUtil.java   View Source Code Vote up 5 votes
/**
 * 得到字段的绑定名称,如果含有{@linkplain ExceptDBField}注解则会返回null。
 *
 * @param field 使用{@linkplain PortInObj.Nece}、{@linkplain DBField}或{@linkplain PortInObj.UnNece
 *              }注解标注字段,使用{@linkplain DBField}来映射数据库字段名。
 */
public static String getTiedName(Field field)
{
    if (field.isAnnotationPresent(ExceptDBField.class))
    {
        return null;
    }
    field.setAccessible(true);
    String name = null;
    if (field.isAnnotationPresent(PortInObj.Nece.class))
    {
        name = PortUtil.tied(field.getAnnotation(PortInObj.Nece.class), field, true);
    } else if (field.isAnnotationPresent(PortInObj.UnNece.class))
    {
        name = PortUtil.tied(field.getAnnotation(PortInObj.UnNece.class), field, true);
    } else if (field.isAnnotationPresent(DBField.class))
    {
        name = field.getName();
        DBField dbField = field.getAnnotation(DBField.class);
        if (!dbField.value().equals(""))
        {
            name = dbField.value();
        }
    }

    return name;
}
 
Example 5
Project: sf-java-ui   File: TextAreaGenerator.java   View Source Code Vote up 5 votes
@Override
public void generate(ObjectNode fieldFormDefinition, Field field) {
	TextArea annotation = field.getAnnotation(TextArea.class);
	fieldFormDefinition.put("key", field.getName());
	fieldFormDefinition.put("type", "textarea");

	String fieldAddonLeft = annotation.fieldAddonLeft();
	if (!fieldAddonLeft.isEmpty()) {
		fieldFormDefinition.put("fieldAddonLeft", fieldAddonLeft);
	}
	
	String fieldAddonRight = annotation.fieldAddonRight();
	if (!fieldAddonRight.isEmpty()) {
		fieldFormDefinition.put("fieldAddonRight", fieldAddonRight);
	}
	
	String description = annotation.description();
	if (!description.isEmpty()) {
		fieldFormDefinition.put("description", description);
	}
	String placeHolder = annotation.placeHolder();
	if (!placeHolder.isEmpty()) {
		fieldFormDefinition.put("placeholder", placeHolder);
	}
	boolean noTitle = annotation.noTitle();
	if (noTitle) {
		fieldFormDefinition.put("notitle", noTitle);
	}
	String validationMessage = annotation.validationMessage();
	if (!validationMessage.isEmpty()) {
		fieldFormDefinition.put("validationMessage", validationMessage);
	}
	boolean readOnly = annotation.readOnly();
	if (readOnly) {
		fieldFormDefinition.put("readonly", readOnly);
	}
}
 
Example 6
Project: mybatis-dynamic-query   File: EntityHelper.java   View Source Code Vote up 5 votes
static Column getColumnByProperty(final String propertyName, final Field[] properties) {
    Field matchProperty = getPropertyField(propertyName, properties);
    if (matchProperty.isAnnotationPresent(Column.class)) {
        return matchProperty.getAnnotation(Column.class);
    }

    return null;
}
 
Example 7
Project: hibatis   File: IdProperty.java   View Source Code Vote up 5 votes
public IdProperty(EntityMetadata metadata , Field field){
	super(metadata , field);
	Id id = field.getAnnotation(Id.class);
	if(id.useGeneratedKeys()){
		keyGenerator  = new Jdbc3KeyGenerator();
	}
}
 
Example 8
Project: olingo-jpa   File: JpaEntityCsdlProvider.java   View Source Code Vote up 5 votes
private CsdlPropertyRef extractKey(Field f) throws CsdlExtractException {
    ODataProperty prop = f.getAnnotation(ODataProperty.class);
    if (prop == null) {
        throw new CsdlExtractException("Field annotated as ODataKey must be annotated as ODataProperty as well");
    }
    return new CsdlPropertyRef().setName(prop.name());
}
 
Example 9
Project: javadoc2swagger   File: DefinitionParser.java   View Source Code Vote up 5 votes
/**
 * Processes all fields of a class
 * 
 * @param fields
 *            array of fields
 * @param definition
 *            current definition
 * @param rootDefinition
 *            definition where the recursion started to prevent an endless
 *            loop
 * @return list of {@link Property} objects
 * @throws ParserException
 *             Error while the parsing process
 */
public List<Property> processFields(Field[] fields, Definition definition, Definition rootDefinition)
        throws ParserException {
    DataTypeFactory typeHandler = new DataTypeFactory();
    List<Property> properties = new ArrayList<>();
    for (Field field : fields) {
        if (field.getAnnotation(JsonIgnore.class) == null && field.getAnnotation(JsonBackReference.class) == null) {
            Property property = new Property();
            Class<?> typeClass = field.getType();
            Annotation[] annotations = field.getAnnotations();
            Type genericType = field.getGenericType();
            processGenerics(genericType, property, definition, rootDefinition);
            DataType typeObject = typeHandler.getDataType(typeClass.getName());
            String type = typeObject.getType();
            String name = field.getName();
            property.setName(name);
            if (type.length() > 14 && (type.substring(14).equals(definition.getClassName())
                    || type.substring(14).equals(rootDefinition.getClassName()))) {
                property.setReference(type);
            } else if (type.startsWith("#")) {
                createDefinitionBySchemaAndPackageIfNotExists(type, typeClass.getTypeName(), rootDefinition);
                property.setReference(type);
            } else {
                property.setType(type);
                property.setFormat(typeObject.getFormat());
            }
            properties.add(property);
            processAnnotations(annotations, definition, name);
        }
    }
    return properties;
}
 
Example 10
Project: oscm   File: ReferenceTest.java   View Source Code Vote up 5 votes
@Test
public void testCreateForPersistenceContextField2() throws Exception {
    class Bean {
        @PersistenceContext(name = "other")
        private Object foo;
    }
    Field field = Bean.class.getDeclaredField("foo");
    PersistenceContext ctx = field.getAnnotation(PersistenceContext.class);
    Reference r = Reference.createFor(ctx, field);
    assertEquals(EntityManager.class, r.getInterfaceOrClass());
    assertEquals("other", r.getName());
}
 
Example 11
Project: lyra2-java   File: CommandLine.java   View Source Code Vote up 5 votes
/** Calls {@link #addPositionalParameter(Field, CommandLine.Help.IParamLabelRenderer)} for all non-hidden ConsoleArgs in the list.
 * @param fields fields annotated with {@link Parameters} to add usage descriptions for
 * @param paramLabelRenderer knows how to render option parameters */
public void addPositionalParameters(List<Field> fields, IParamLabelRenderer paramLabelRenderer) {
    for (Field field : fields) {
        Parameters parameters = field.getAnnotation(Parameters.class);
        if (!parameters.hidden()) {
            addPositionalParameter(field, paramLabelRenderer);
        }
    }
}
 
Example 12
Project: vind   File: DefaultIdGenerator.java   View Source Code Vote up 5 votes
@Override
public String decompose(String idValue, Field idField, Class<?> clazz) {
    final Id id = idField.getAnnotation(Id.class);
    if (id == null) {
        throw new IllegalArgumentException("Missing Id-annotation on Id-annotated field? Weird...");
    } else {
        return idValue.substring(id.prefix().length(), idValue.length() - id.suffix().length());
    }
}
 
Example 13
Project: B4zV4lidator   File: B4zV4lidatorUtil.java   View Source Code Vote up 5 votes
public static Annotation getAnnotationRuleFromField(final Object obj, final Field field,
		final Class<? extends Annotation> annotation) {

	Annotation anno = null;
	try {
		final Annotation annoField = field.getAnnotation(annotation);
		final Annotation annoMethod = obj.getClass()
				.getDeclaredMethod(B4zV4lidatorUtil.getMethod(obj, field).getName()).getAnnotation(annotation);
		anno = Objects.nonNull(annoField) ? annoField : annoMethod;
	} catch (SecurityException | NoSuchMethodException e) {
		e.printStackTrace();
	}
	return anno;
}
 
Example 14
Project: ModifiableVariable   File: ModifiableVariableAnalyzer.java   View Source Code Vote up 5 votes
/**
 * Returns a list of all the modifiable variable holders in the object,
 * including this instance.
 * 
 * @param object
 *            Analyzed object
 * @return A list of objects with their modifiable variable fields (only
 *         objects with modifiable variables are selected)
 */
public static List<ModifiableVariableListHolder> getAllModifiableVariableHoldersRecursively(Object object) {
    List<ModifiableVariableListHolder> holders = new LinkedList<>();
    List<Field> modFields = getAllModifiableVariableFields(object);
    if (!modFields.isEmpty()) {
        holders.add(new ModifiableVariableListHolder(object, modFields));
    }
    List<Field> allFields = ReflectionHelper.getFieldsUpTo(object.getClass(), null, null);
    for (Field f : allFields) {
        try {
            HoldsModifiableVariable holdsVariable = f.getAnnotation(HoldsModifiableVariable.class);
            f.setAccessible(true);
            Object possibleHolder = f.get(object);
            if (possibleHolder != null && holdsVariable != null) {
                if (possibleHolder instanceof List) {
                    holders.addAll(getAllModifiableVariableHoldersFromList((List) possibleHolder));
                } else if (possibleHolder.getClass().isArray()) {
                    holders.addAll(getAllModifiableVariableHoldersFromArray((Object[]) possibleHolder));
                } else {
                    holders.addAll(getAllModifiableVariableHoldersRecursively(possibleHolder));
                }
            }
        } catch (IllegalAccessException | IllegalArgumentException ex) {
            LOGGER.debug("Accessing field {} of type {} not possible: {}", f.getName(), f.getType(), ex.toString());
        }
    }
    return holders;
}
 
Example 15
Project: testee.fi   File: AnnotationUtils.java   View Source Code Vote up 5 votes
public static Map<Class<? extends Annotation>, Collection<Field>> groupByAnnotation(
        final Collection<Field> fields,
        final Class<? extends Annotation>... annotations
) {
    final Map<Class<? extends Annotation>, Collection<Field>> ret = new HashMap<>();
    for (final Class<? extends Annotation> annotation : annotations) {
        ret.put(annotation, new HashSet<>());
        for (final Field field : fields) {
            if (field.getAnnotation(annotation) != null) {
                ret.get(annotation).add(field);
            }
        }
    }
    return ret;
}
 
Example 16
Project: GitHub   File: IncludeJsr305AnnotationsIT.java   View Source Code Vote up 5 votes
private static void validateNonnullField(Field nonnullField) {
    Nonnull nonnullAnnotation = nonnullField.getAnnotation(Nonnull.class);
    Nullable nullableAnnotation = nonnullField.getAnnotation(Nullable.class);

    assertNotNull("Expected @Nonnull annotation is missing.", nonnullAnnotation);
    assertNull("Unexpected @Nullable annotation found.", nullableAnnotation);
}
 
Example 17
Project: GitHub   File: SQLiteUtils.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public static String createColumnDefinition(TableInfo tableInfo, Field field) {
	StringBuilder definition = new StringBuilder();

	Class<?> type = field.getType();
	final String name = tableInfo.getColumnName(field);
	final TypeSerializer typeSerializer = Cache.getParserForType(field.getType());
	final Column column = field.getAnnotation(Column.class);

	if (typeSerializer != null) {
		type = typeSerializer.getSerializedType();
	}

	if (TYPE_MAP.containsKey(type)) {
		definition.append(name);
		definition.append(" ");
		definition.append(TYPE_MAP.get(type).toString());
	}
	else if (ReflectionUtils.isModel(type)) {
		definition.append(name);
		definition.append(" ");
		definition.append(SQLiteType.INTEGER.toString());
	}
	else if (ReflectionUtils.isSubclassOf(type, Enum.class)) {
		definition.append(name);
		definition.append(" ");
		definition.append(SQLiteType.TEXT.toString());
	}

	if (!TextUtils.isEmpty(definition)) {

		if (name.equals(tableInfo.getIdName())) {
			definition.append(" PRIMARY KEY AUTOINCREMENT");
		}else if(column!=null){
			if (column.length() > -1) {
				definition.append("(");
				definition.append(column.length());
				definition.append(")");
			}

			if (column.notNull()) {
				definition.append(" NOT NULL ON CONFLICT ");
				definition.append(column.onNullConflict().toString());
			}

			if (column.unique()) {
				definition.append(" UNIQUE ON CONFLICT ");
				definition.append(column.onUniqueConflict().toString());
			}
		}

		if (FOREIGN_KEYS_SUPPORTED && ReflectionUtils.isModel(type)) {
			definition.append(" REFERENCES ");
			definition.append(Cache.getTableInfo((Class<? extends Model>) type).getTableName());
			definition.append("("+tableInfo.getIdName()+")");
			definition.append(" ON DELETE ");
			definition.append(column.onDelete().toString().replace("_", " "));
			definition.append(" ON UPDATE ");
			definition.append(column.onUpdate().toString().replace("_", " "));
		}
	}
	else {
		Log.e("No type mapping for: " + type.toString());
	}

	return definition.toString();
}
 
Example 18
Project: CustomWorldGen   File: ILanguageAdapter.java   View Source Code Vote up 4 votes
@Override
public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader)
{
    // For Scala mods, we want to enable authors to write them like so:
    // object ModName {
    //   @SidedProxy(...)
    //   var proxy: ModProxy = null
    // }
    // For this to work, we have to search inside the inner class Scala
    // generates for singletons, which is in called ModName$. These are
    // not automatically handled, because the mod discovery code ignores
    // internal classes.
    // Note that it is alternatively possible to write this like so:
    // class ModName {
    //   @SidedProxy(...)
    //   var proxy: ModProxy = null
    // }
    // object ModName extends ModName { ... }
    // which will fall back to the normal injection code which calls
    // setProxy in turn.

    // Get the actual mod implementation, which will be the inner class
    // if we have a singleton.
    Class<?> proxyTarget = mod.getMod().getClass();
    if (proxyTarget.getName().endsWith("$"))
    {
        // So we have a singleton class, check if there are targets.
        for (Field target : proxyTarget.getDeclaredFields())
        {
            // This will not turn up anything if the alternative
            // approach was taken (manually declaring the class).
            // So we don't initialize the field twice.
            if (target.getAnnotation(SidedProxy.class) != null)
            {
                String targetType = side.isClient() ? target.getAnnotation(SidedProxy.class).clientSide() : target.getAnnotation(SidedProxy.class).serverSide();
                try
                {
                    Object proxy = Class.forName(targetType, true, loader).newInstance();

                    if (!target.getType().isAssignableFrom(proxy.getClass()))
                    {
                        FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, proxyTarget.getSimpleName(), target.getName());
                        throw new LoaderException(String.format("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, proxyTarget.getSimpleName(), target.getName()));
                    }

                    setProxy(target, proxyTarget, proxy);
                }
                catch (Exception e) {
                    FMLLog.log(Level.ERROR, e, "An error occurred trying to load a proxy into %s.%s", proxyTarget.getSimpleName(), target.getName());
                    throw new LoaderException(e);
                }
            }
        }
    }
    else
    {
        FMLLog.finer("Mod does not appear to be a singleton.");
    }
}
 
Example 19
Project: xbot_head   File: Indication.java   View Source Code Vote up 4 votes
public static boolean asArray(Field f) {
    return (f.getAnnotation(AsArray.class) != null);
}
 
Example 20
Project: mybatisx   File: ExprBuilder.java   View Source Code Vote up 4 votes
private void generateJoinSql(Class<?> joinClazz,TableDetail beforeTd,TableDetail joinTd,String propName) throws Exception{
	String[] tables=joinSql.toString().split("join "+joinClazz.getSimpleName()+" ");
	String tableAlias=joinClazz.getSimpleName()+tables.length;
	joinTd.alias=tableAlias;
	Field beforeField=beforeTd.clazz.getDeclaredField(propName);
	org.cabbage.mybatisx.core.annotation.Field beforeFieldAnno=beforeField.getAnnotation(org.cabbage.mybatisx.core.annotation.Field.class);
	org.cabbage.mybatisx.core.annotation.ManyToMany beforeFieldAnnoMany=beforeField.getAnnotation(org.cabbage.mybatisx.core.annotation.ManyToMany.class);
	org.cabbage.mybatisx.core.annotation.OneToMany beforeFieldAnnoOneToMany=beforeField.getAnnotation(org.cabbage.mybatisx.core.annotation.OneToMany.class);
	
	Table joinTableAnno=joinClazz.getAnnotation(Table.class);				
	String joinTable=joinTableAnno.value();
	
	List<Field> primaryFields= EntityUtils.getPrimaryField(joinClazz);
	
	if(primaryFields.size()!=1){
		throw new EntityException(" 该方法暂不支持多个主键和没有主键 ");
	}
	org.cabbage.mybatisx.core.annotation.Field joinTablePrimaryFieldAnno= primaryFields.get(0).getAnnotation(org.cabbage.mybatisx.core.annotation.Field.class);
	
	if(beforeFieldAnno !=null){
		
		joinSql.append(" join "+joinTable+ " as " +tableAlias+" on "+tableAlias+"."+joinTablePrimaryFieldAnno.value()+"="+beforeTd.alias+"."+beforeFieldAnno.value());
	}
	
	if(beforeFieldAnnoMany !=null){
		Table joinTableAnnoMany = beforeFieldAnnoMany.table().getAnnotation(Table.class);
		String joinTableMany = joinTableAnnoMany.value();
		String tableAliasMany=beforeFieldAnnoMany.table().getSimpleName()+tables.length;
		//查询主表主键
		List<Field> beforePrimaryField= EntityUtils.getPrimaryField(beforeTd.clazz);
		String beforePrimaryFieldValue = beforePrimaryField.get(0).getAnnotation(org.cabbage.mybatisx.core.annotation.Field.class).value();
		
		List<Field> joinPrimaryField= EntityUtils.getPrimaryField(joinTd.clazz);
		String joinPrimaryFieldValue = joinPrimaryField.get(0).getAnnotation(org.cabbage.mybatisx.core.annotation.Field.class).value();
		joinSql.append(" join " + joinTableMany + " as " + tableAliasMany + 
				" on " + tableAliasMany + "."+beforePrimaryFieldValue +"="+beforeTd.alias+"."+beforePrimaryFieldValue+
				" join " +joinTable +" as "+tableAlias+" on "+tableAlias+"."+joinTablePrimaryFieldAnno.value()+"="+tableAliasMany+"."+joinPrimaryFieldValue);
	}
	
	if(beforeFieldAnnoOneToMany!=null){
		Field joinField=joinClazz.getDeclaredField(beforeFieldAnnoOneToMany.field());
		org.cabbage.mybatisx.core.annotation.Field beforeIDField=joinField.getAnnotation(org.cabbage.mybatisx.core.annotation.Field.class);

		joinSql.append(" join "+joinTable+ " as " +tableAlias+" on "+tableAlias+"."+joinTablePrimaryFieldAnno.value()+"="+beforeTd.alias+"."+beforeIDField.value());
	}
	
}