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

The following are Jave code examples for showing how to use getDeclaredAnnotations() 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: SugarOnRest   File: ModuleInfo.java   View Source Code Vote up 6 votes
/**
 * Gets json names from module fields annotations.
 *
 * @param type The Java module type.
 * @return List of json property names.
 */
private static List<ModuleProperty> getFieldAnnotations(Class type) {
    List<ModuleProperty> modelProperties = new ArrayList<ModuleProperty>();
    Field[] fields = type.getDeclaredFields();
     for(Field field : fields) {
        Annotation[] annotations = field.getDeclaredAnnotations();

        for(Annotation annotation : annotations){
            if(annotation instanceof JsonProperty){
                JsonProperty property = (JsonProperty) annotation;
                ModuleProperty moduleProperty = new ModuleProperty();
                moduleProperty.name = field.getName();
                moduleProperty.jsonName = property.value();
                moduleProperty.type = field.getType();
                moduleProperty.isNumeric = isTypeNumeric(field.getType());
                modelProperties.add(moduleProperty);
            }
        }
    }

    return modelProperties;
}
 
Example 2
Project: vertx-zero   File: AffluxThread.java   View Source Code Vote up 6 votes
private void scanSpecific(final Field field) {
    // Vert.x Defined
    final Set<Class<? extends Annotation>> defineds
            = Plugins.INFIX_MAP.keySet();
    final Annotation[] annotations = field.getDeclaredAnnotations();
    // Annotation counter
    final Set<String> set = new HashSet<>();
    final Annotation hitted = Observable.fromArray(annotations)
            .filter(annotation -> defineds.contains(annotation.annotationType()))
            .map(annotation -> {
                set.add(annotation.annotationType().getName());
                return annotation;
            }).blockingFirst();
    // Duplicated annotated
    Fn.flingUp(Values.ONE < set.size(), LOGGER,
            MultiAnnotatedException.class, getClass(),
            field.getName(), field.getDeclaringClass().getName(), set);
    // Fill typed directly.
    LOGGER.info(Info.SCANED_FIELD, this.reference,
            field.getName(),
            field.getDeclaringClass().getName(),
            hitted.annotationType().getName());
    this.fieldMap.put(field.getName(), field.getType());
}
 
Example 3
Project: AquamarineLake   File: MentionedClass.java   View Source Code Vote up 6 votes
public MentionedClass()
{
    for (Field f : this.getClass().getDeclaredFields())
    {
        for (Annotation ann : f.getDeclaredAnnotations())
        {
            if (ann instanceof Mentioned)
            {
                try
                {
                    System.out.println("[Reflection] " + f.getType().getName() + " " + f.getName() + " = " + f.get(this));
                }
                catch(IllegalAccessException e)
                {}
            }
        }
    }
}
 
Example 4
Project: minijax   File: ConstructorProviderBuilder.java   View Source Code Vote up 6 votes
private static boolean isInjectedField(final Field field) {
    for (final Annotation a : field.getDeclaredAnnotations()) {
        final Class<?> t = a.annotationType();
        if (t == javax.inject.Inject.class ||
                t == javax.ws.rs.core.Context.class ||
                t == javax.ws.rs.CookieParam.class ||
                t == javax.ws.rs.FormParam.class ||
                t == javax.ws.rs.HeaderParam.class ||
                t == javax.ws.rs.QueryParam.class ||
                t == javax.ws.rs.PathParam.class ||
                t == javax.ws.rs.BeanParam.class ||
                t == OptionalClasses.PERSISTENCE_CONTEXT) {
            return true;
        }
    }
    return false;
}
 
Example 5
Project: PetBlocks   File: ReflectionUtils.java   View Source Code Vote up 5 votes
/**
 * Invokes the annotation of the given field
 *
 * @param field           field
 * @param annotationClazz annotation
 * @param <T>             returnType
 * @return returnValue
 */
public static <T extends Annotation> T invokeAnnotationByField(Field field, Class<T> annotationClazz) {
    if (field == null)
        throw new IllegalArgumentException("Field cannot be null!");
    if (annotationClazz == null)
        throw new IllegalArgumentException("AnnotationClass cannot be null!");
    for (final Annotation annotation : field.getDeclaredAnnotations()) {
        if (annotation.annotationType() == annotationClazz)
            return (T) annotation;
    }
    return null;
}
 
Example 6
Project: Core-Java   File: FrameworkAnnotationResolver.java   View Source Code Vote up 5 votes
private void checkVariable(Class clazz) {
    List<AnnotationField> annotationFields = (List<AnnotationField>) annotationObjectMap.get(AnnotationObjectType.FIELD);
    if(annotationFields == null){
        annotationFields = new ArrayList<>();
    }
    Field[] fields = clazz.getDeclaredFields();
    if(fields== null || fields.length == 0){
        return;
    }
    for (Field field : fields){
        Annotation[] annotations = field.getDeclaredAnnotations();
        if(annotations== null || annotations.length==0)
            continue;
        for (int i=0;i<annotations.length;i++){
            Class<? extends Annotation> annotationType = annotations[i].annotationType();
            if(annotationType.equals(Autowired.class)){
                AnnotationField annotationField = AnnotationField.builder()
                                                    .belongClassName(clazz.getName())
                                                    .variableClassName(field.getType().getName())
                                                    .variableName(field.getName())
                                                    .build();
                annotationFields.add(annotationField);
            }
        }
    }
    annotationObjectMap.put(AnnotationObjectType.FIELD, annotationFields);
}
 
Example 7
Project: vertx-zero   File: AffluxScatter.java   View Source Code Vote up 5 votes
private Class<? extends Annotation> search(
        final Field field
) {
    final Annotation[] annotations = field.getDeclaredAnnotations();
    final Set<Class<? extends Annotation>>
            annotationCls = Plugins.INFIX_MAP.keySet();
    Class<? extends Annotation> hitted = null;
    for (final Annotation annotation : annotations) {
        if (annotationCls.contains(annotation.annotationType())) {
            hitted = annotation.annotationType();
            break;
        }
    }
    return hitted;
}
 
Example 8
Project: Ink   File: BeanDefinitionReader.java   View Source Code Vote up 5 votes
public void configureInjectField() {
    for (Class class1 : classList) {
        log.info("{} is being configure", class1);
        BeanMetaData metaData = getMetaData(class1);
        for (Field field : metaData.getFields()) {
            Annotation[] annotations = field.getDeclaredAnnotations();
            for ( Annotation annotation : annotations) {
                if (annotation instanceof Inject) {
                    try {
                        field.setAccessible(true);
                        //先从containner中寻找bean
                        Object object = this.register.getBean(Class.forName(field.getGenericType().toString().split(" ")[1]));

                        if (object == null) {
                            object = this.register.getBean(field.getType().getName());
                        }
                        //如果没找到,则new一个
                        if (object == null) {
                            object = Class.forName(field.getGenericType().toString().split(" ")[1]).newInstance();
                        }

                        field.set(this.register.getBean(class1), object);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

}
 
Example 9
Project: BlockBall   File: ReflectionUtils.java   View Source Code Vote up 5 votes
/**
 * Invokes the annotation of the given field
 *
 * @param field           field
 * @param annotationClazz annotation
 * @param <T>             returnType
 * @return returnValue
 */
public static <T extends Annotation> T invokeAnnotationByField(Field field, Class<T> annotationClazz) {
    if (field == null)
        throw new IllegalArgumentException("Field cannot be null!");
    if (annotationClazz == null)
        throw new IllegalArgumentException("AnnotationClass cannot be null!");
    for (final Annotation annotation : field.getDeclaredAnnotations()) {
        if (annotation.annotationType() == annotationClazz)
            return (T) annotation;
    }
    return null;
}
 
Example 10
Project: sirocco   File: FieldSupport.java   View Source Code Vote up 5 votes
public static Annotation[] getAnnotations(Field f, Class<?> filterBy, boolean inherits)
{
	ArrayList<Annotation> filteredAnns = new ArrayList<Annotation>();
	
	Annotation[] allAnns = (inherits ? f.getAnnotations() : f.getDeclaredAnnotations());
	
	for (Annotation ann : allAnns) {
		if (filterBy.isAssignableFrom(ann.annotationType()))
			filteredAnns.add(ann);
	}
	return allAnns;
	
}
 
Example 11
Project: openjdk-jdk10   File: HotSpotResolvedJavaFieldImpl.java   View Source Code Vote up 5 votes
@Override
public Annotation[] getDeclaredAnnotations() {
    Field javaField = toJava();
    if (javaField != null) {
        return javaField.getDeclaredAnnotations();
    }
    return new Annotation[0];
}
 
Example 12
Project: AstralEdit   File: ReflectionUtils.java   View Source Code Vote up 5 votes
/**
 * Invokes the annotation of the given field
 *
 * @param field           field
 * @param annotationClazz annotation
 * @param <T>             returnType
 * @return returnValue
 */
public static <T extends Annotation> T invokeAnnotationByField(Field field, Class<T> annotationClazz) {
    if (field == null)
        throw new IllegalArgumentException("Field cannot be null!");
    if (annotationClazz == null)
        throw new IllegalArgumentException("AnnotationClass cannot be null!");
    for (final Annotation annotation : field.getDeclaredAnnotations()) {
        if (annotation.annotationType() == annotationClazz)
            return (T) annotation;
    }
    return null;
}
 
Example 13
Project: openjdk-systemtest   File: AnnotationFieldTests.java   View Source Code Vote up 4 votes
public void testField3() throws NoSuchFieldException
{		
	Field myField = AnnotatedElements.class.getDeclaredField("field3");
	Annotation[] annotationArray = null;
	annotationArray = myField.getDeclaredAnnotations();
	int NumExpectedAnnotations = 0;
	try
	{
		NumExpectedAnnotations = myField.getInt(null);
	}
	catch (Exception e)
	{
		fail("Error in retrieving int value from field3!");
	}
	// Make sure the number of annotations is the same as the number in the returned array
	assertTrue( NumExpectedAnnotations == annotationArray.length);			
	for (int j=0; j<annotationArray.length; j++)
	{
		if (annotationArray[j] instanceof A5)
		{
			A5 a = (A5) annotationArray[j];
			assertTrue(a.priority() == Priority.MEDIUM);					
			assertTrue(a.createdBy().equalsIgnoreCase("Bob Bobson"));					
		}
	}
	Annotation myAnnotation = null;
	myAnnotation = myField.getAnnotation(A0.class);
	assertTrue(myAnnotation != null);
	
	myField.getDeclaredAnnotations();
	
	myAnnotation = myField.getAnnotation(A1.class);
	assertTrue(myAnnotation != null);	
	myAnnotation = myField.getAnnotation(A2.class);
	assertTrue(myAnnotation != null);
	myAnnotation = myField.getAnnotation(A3.class);
	assertTrue(myAnnotation != null);
	
	myField.getDeclaredAnnotations();
	
	myAnnotation = myField.getAnnotation(A4.class);
	assertTrue(myAnnotation != null);		
	myAnnotation = myField.getAnnotation(A5.class);
	assertTrue(myAnnotation != null);
}
 
Example 14
Project: MagicBox   File: Secy.java   View Source Code Vote up 4 votes
private StateField analyseField(@NonNull Field field, String tag) {
    if (!field.isAnnotationPresent(KeepState.class))
        return null;
    KeepState keepStateNotation = null;
    for (Annotation notation : field.getDeclaredAnnotations()) {
        if (notation.annotationType().equals(KeepState.class)) {
            keepStateNotation = (KeepState) notation;
            break;
        }
    }

    if (keepStateNotation == null)
        throw new MException("check logic,keepStateNotation is not supposed to be null");

    String fieldName = field.getName();
    String bundleKey = "key_" + tag + "#" + fieldName;

    Type type = keepStateNotation.type();

    if (type == Type.Infer)
        type = TypeInferUtils.infer(field);
    else if (type == Type.Object) {
        try {
            return analyseCustoms(field, keepStateNotation);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
            throw new MException(e.getMessage());
        }
    } else {
        if (type.canBeChecked()) {
            boolean isCorrectType = type.check(field);
            if (!isCorrectType) {
                MagicBox.getLogger().error("", "unCorrect Type set for" + fieldName);
                return new StateField(fieldName, field, bundleKey, Type.Infer);
            }
        } else {
            MagicBox.getLogger().debug("", "you have notated " + fieldName + " as " + type.name() +
                    ", one cannot be checked, with cautions");
        }
    }

    return new StateField(fieldName, field, bundleKey, type);
}
 
Example 15
Project: DailyStudy   File: TableCreator.java   View Source Code Vote up 4 votes
public static void main(String[] args) {
    Member member = new Member();
    String[] classNames = {member.getClass().getName()};

    for (String className : classNames) {
        try {
            Class clazz = Class.forName(className);
            DBTable dbTable = (DBTable) clazz.getAnnotation(DBTable.class);
            if (dbTable == null) {
                System.out.println("no dbtable class");
                return;
            }
            String tableName = dbTable.name();
            if (tableName.length() < 1)
                tableName = clazz.getName().toUpperCase();
            List<String> columnDefs = new ArrayList<>();
            for (Field field : clazz.getDeclaredFields()) {
                String columnName = null;
                Annotation[] anns = field.getDeclaredAnnotations();
                if (anns.length < 1) {
                    continue;
                }
                if (anns[0] instanceof SQLInteger) {
                    SQLInteger integer = (SQLInteger) anns[0];
                    if (integer.name().length() < 1)
                        columnName = field.getName().toUpperCase();
                    else
                        columnName = integer.name();
                    columnDefs.add(columnName + " INT" + getConstraints(integer.constraints()));
                }

                if (anns[0] instanceof SQLString) {
                    SQLString string = (SQLString) anns[0];
                    if (string.name().length() < 1)
                        columnName = field.getName().toUpperCase();
                    else
                        columnName = string.name();
                    columnDefs.add(columnName + " VARCHAR(" + string.value() + ")" + getConstraints(string.constraints()));
                }
                StringBuilder createCommand  = new StringBuilder("CREATE TABLE " + tableName + "(");
                for (String columndef : columnDefs) {
                    createCommand.append("\n     " + columndef + ",");
                }
                String tableCreate = createCommand.substring(0, createCommand.length() - 1) + ")";
                System.out.println(tableCreate.toString());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
 
Example 16
Project: renovate2   File: ObjectParser.java   View Source Code Vote up 4 votes
ObjectParser build() {
            for (Annotation annotation : objectAnnotations) {
                parseHttpAnnotation(annotation);
            }
            if (httpMethod == null) {
                throw objectError("HTTP method annotation is required (e.g., @GET, @POST, etc.).");
            }
//            if hasBody is true then skip ,if false then isMultipart and isFromEncoded not true
            if (!hasBody) { //if false ,no body,but has multipart or fromEncoded append err
                if (isMultipart) {
                    throw objectError(
                            "Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
                }
                if (isFormEncoded) {
                    throw objectError("FormUrlEncoded can only be specified on HTTP methods with "
                            + "request body (e.g., @POST).");
                }
            }

            int fieldCount = fields.length;
            for (int p = 0; p < fieldCount; p++) {
                Field field = fields[p];
                Annotation[] annotations = field.getDeclaredAnnotations();
                if (annotations == null || annotations.length == 0) {
                    System.out.println(String.format("field %s no renovate annotation found", field.getName()));
                    continue;
                } else if (field.isAnnotationPresent(Ignore.class)) {
                    System.out.println(String.format("field %s,%s is ignored", clazz.getName(), field.getName()));
                    continue;
                }
                fieldParameterHandlerMap.put(field, parseParameter(p, field.getType(), annotations, field));
            }
            if (relativeUrl == null && !gotUrl) {
                throw objectError("Missing either @%s URL or @Url parameter.", httpMethod);
            }
            if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
                throw objectError("Non-body HTTP method cannot contain @Body.");
            }
            if (isFormEncoded && !gotField) {
                throw objectError("Form-encoded method must contain at least one @Params.");
            }
            if (isMultipart && !gotPart) {
                throw objectError("Multipart method must contain at least one @Part.");
            }

            return new ObjectParser(this);
        }