Example usage for java.lang.reflect Field getDeclaredAnnotation

List of usage examples for java.lang.reflect Field getDeclaredAnnotation

Introduction

In this page you can find the example usage for java.lang.reflect Field getDeclaredAnnotation.

Prototype

@Override
public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:com.shenit.commons.utils.GsonUtils.java

/**
 * ???./*  ww  w.j  a v  a2s .c o  m*/
 * @param clazz
 * @return
 */
public static Field<?>[] serializeFields(Class<?> clazz) {
    if (REGISTERED_FIELDS.containsKey(clazz))
        return REGISTERED_FIELDS.get(clazz);
    java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
    List<Field<?>> fs = Lists.newArrayList();
    SerializedName serializedName;
    JsonProperty jsonProp;
    IgnoreField ignore;
    for (java.lang.reflect.Field field : fields) {
        if (field == null)
            continue;
        serializedName = field.getAnnotation(SerializedName.class);
        jsonProp = field.getAnnotation(JsonProperty.class);
        ignore = field.getAnnotation(IgnoreField.class);
        if (ignore != null)
            continue;
        String name = null;
        if (serializedName != null) {
            name = serializedName.value();
        } else if (jsonProp != null) {
            name = jsonProp.value();
        } else {
            name = Modifier.isStatic(field.getModifiers()) ? null : field.getName();
        }
        if (name == null)
            continue;

        Default defVal = field.getDeclaredAnnotation(Default.class);
        fs.add(new Field(name, field.getName(), field.getType(), defVal == null ? null : defVal.value()));
    }
    Field<?>[] fsArray = fs.toArray(new Field<?>[0]);
    REGISTERED_FIELDS.put(clazz, fsArray);
    return fsArray;
}

From source file:org.jnosql.artemis.reflection.DefaultFieldRepresentation.java

DefaultFieldRepresentation(FieldType type, Field field, String name) {
    super(type, field, name);
    this.key = field.getDeclaredAnnotation(Key.class) != null;
}

From source file:com.qwazr.search.annotations.AnnotatedIndexService.java

/**
 * Create a new index service. A class with Index and IndexField annotations.
 *
 * @param indexService         the IndexServiceInterface to use
 * @param indexDefinitionClass an annotated class
 *///  w  w w.  j  a  v a 2s. c  o m
public AnnotatedIndexService(IndexServiceInterface indexService, Class<T> indexDefinitionClass) {
    Objects.requireNonNull(indexService, "The indexService parameter is null");
    Objects.requireNonNull(indexDefinitionClass, "The indexDefinition parameter is null");
    this.indexService = indexService;
    this.annotatedService = indexService instanceof AnnotatedServiceInterface
            ? (AnnotatedServiceInterface) indexService
            : null;
    this.indexDefinitionClass = indexDefinitionClass;
    Index index = indexDefinitionClass.getAnnotation(Index.class);
    Objects.requireNonNull(index, "This class does not declare any Index annotation: " + indexDefinitionClass);
    schemaName = index.schema();
    indexName = index.name();
    similarityClass = index.similarityClass();
    Field[] fields = indexDefinitionClass.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        fieldMap = new HashMap<>();
        indexFieldMap = new HashMap<>();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(IndexField.class))
                continue;
            field.setAccessible(true);
            IndexField indexField = field.getDeclaredAnnotation(IndexField.class);
            String indexName = StringUtils.isEmpty(indexField.name()) ? field.getName() : indexField.name();
            indexFieldMap.put(indexName, indexField);
            fieldMap.put(indexName, field);
        }
    } else {
        fieldMap = null;
        indexFieldMap = null;
    }
}

From source file:com.fitbur.testify.integration.IntegrationTestVerifier.java

@Override
public void configuration() {
    doPrivileged((PrivilegedAction<Object>) () -> {
        String testClassName = testContext.getTestClassName();
        CutDescriptor cutDescriptor = testContext.getCutDescriptor();
        Collection<FieldDescriptor> fieldDescriptors = testContext.getFieldDescriptors().values();

        if (testContext.getCutCount() == 1) {
            checkState(testContext.getConstructorCount() == 1,
                    "Class under test '%s' defined in test class '%s' has %s constructors. "
                            + "Please insure that the class under test has one and only one constructor.",
                    cutDescriptor.getTypeName(), testClassName, testContext.getConstructorCount());
        }//from  w  w w.  j a  va 2 s.c o m
        // insure that only one field has Cut annotation on it.
        if (testContext.getCutCount() > 1) {
            checkState(false, "Found more than one class under test in test class %s. Please insure "
                    + "that only one field is annotated with @Cut.", testClassName);
        }

        //insure that there is a field annotated with @Cut defined or one or more
        //fields annotated with @Real or @Inject
        if (testContext.getCutCount() == 0 && fieldDescriptors.isEmpty()) {
            checkState(false,
                    "Test class '%s' does not define a field annotated with @Cut "
                            + "nor does it define field(s) annotated with @Real or @Inject. "
                            + "Please insure the test class defines a single field annotated "
                            + "with @Cut or defines at least one field annotated with @Real " + "or @Inject.",
                    testClassName);
        }

        //insure need providers have default constructors.
        testContext.getAnnotations(Need.class).parallelStream().map(Need::value).forEach(p -> {
            try {
                p.getDeclaredConstructor();
            } catch (NoSuchMethodException e) {
                checkState(false,
                        "Need provider '%s' defined in test class '%s' does not have a "
                                + "zero argument default constructor. Please insure that the need "
                                + "provider defines an accessible zero argument default constructor.",
                        testClassName, p.getSimpleName());
            }
        });

        fieldDescriptors.parallelStream().forEach(p -> {

            Field field = p.getField();
            Class<?> fieldType = p.getType();
            String fieldName = p.getName();
            String fieldTypeName = p.getTypeName();

            checkState(!fieldType.isArray(),
                    "Field '%s' in test class '%s' can not be configured because '%s'"
                            + " is an array. Please consider using a List instead of arrays.",
                    fieldName, testClassName, fieldTypeName);
            Fake fake = field.getDeclaredAnnotation(Fake.class);
            if (fake != null) {
                checkState(!isFinal(fieldType.getModifiers()),
                        "Can not fake field '%s' in test class '%s' because '%s'" + " is a final class.",
                        fieldName, testClassName, fieldTypeName);
            }

            Real real = field.getDeclaredAnnotation(Real.class);
            if (real != null && real.value()) {
                checkState(!isFinal(fieldType.getModifiers()),
                        "Can not create delegated fake of field '%s' in test class '%s' "
                                + "because '%s' is a final class.",
                        fieldName, testClassName, fieldTypeName);
            }
        });

        return null;
    });
}

From source file:com.fitbur.testify.system.SystemTestVerifier.java

@Override
public void configuration() {
    doPrivileged((PrivilegedAction<Object>) () -> {
        String testClassName = testContext.getTestClassName();
        CutDescriptor cutDescriptor = testContext.getCutDescriptor();
        Collection<FieldDescriptor> fieldDescriptors = testContext.getFieldDescriptors().values();

        if (testContext.getCutCount() == 1) {
            checkState(testContext.getConstructorCount() == 1,
                    "Class under test '%s' defined in test class '%s' has %s constructors. "
                            + "Please insure that the class under test has one and only one constructor.",
                    cutDescriptor.getTypeName(), testClassName, testContext.getConstructorCount());
        }/*from w  w  w .  jav  a  2 s. c o  m*/
        // insure that only one field has Cut annotation on it.
        if (testContext.getCutCount() > 1) {
            checkState(false, "Found more than one class under test in %s. Please insure "
                    + "that only one field is annotated with @Cut.", testClassName);
        }

        //insure that there is a field annotated with @Cut defined or one or more
        //fields annotated with @Real or @Inject
        if (testContext.getCutCount() == 0 && fieldDescriptors.isEmpty()) {
            checkState(false,
                    "Test class '%s' does not define a field annotated with @Cut "
                            + "nor does it define field(s) annotated with @Real or @Inject. "
                            + "Please insure the test class defines a single field annotated "
                            + "with @Cut or defines at least one field annotated with @Real " + "or @Inject.",
                    testClassName);
        }

        //insure need providers have default constructors.
        testContext.getAnnotations(Need.class).parallelStream().map(Need::value).forEach(p -> {
            try {
                p.getDeclaredConstructor();
            } catch (NoSuchMethodException e) {
                checkState(false,
                        "Need provider '%s' defined in test class '%s' does not have a "
                                + "zero argument default constructor. Please insure that the need "
                                + "provider defines an accessible zero argument default constructor.",
                        testClassName, p.getSimpleName());
            }
        });

        fieldDescriptors.parallelStream().forEach(p -> {
            Field field = p.getField();
            Class<?> fieldType = p.getType();
            String fieldName = p.getName();
            String fieldTypeName = p.getTypeName();

            checkState(!fieldType.isArray(),
                    "Field '%s' in test class '%s' can not be configured because '%s'"
                            + " is an array. Please consider using a List instead of arrays.",
                    fieldName, testClassName, fieldTypeName);
            Fake fake = field.getDeclaredAnnotation(Fake.class);
            if (fake != null) {
                checkState(!isFinal(fieldType.getModifiers()),
                        "Can not fake field '%s' in test class '%s' because '%s'" + " is a final class.",
                        fieldName, testClassName, fieldTypeName);
            }

            Real real = field.getDeclaredAnnotation(Real.class);
            if (real != null && real.value()) {
                checkState(!isFinal(fieldType.getModifiers()),
                        "Can not create delegated fake of field '%s' in test class '%s' "
                                + "because '%s' is a final class.",
                        fieldName, testClassName, fieldTypeName);
            }

        });

        return null;
    });
}

From source file:com.adaptris.core.runtime.AdapterRegistry.java

@Override
public String getClassDefinition(String className) throws CoreException {
    final ClassDescriptor classDescriptor = new ClassDescriptor(className);
    try {/*from ww w.j  a v  a 2 s  .co  m*/
        Class<?> clazz = Class.forName(className);

        classDescriptor.setClassType(ClassDescriptor.ClassType.getTypeForClass(clazz).name().toLowerCase());

        List<String> displayOrder = new ArrayList<>();
        for (Annotation annotation : clazz.getAnnotations()) {
            if (XStreamAlias.class.isAssignableFrom(annotation.annotationType())) {
                classDescriptor.setAlias(((XStreamAlias) annotation).value());
            } else if (ComponentProfile.class.isAssignableFrom(annotation.annotationType())) {
                classDescriptor.setTags(((ComponentProfile) annotation).tag());
                classDescriptor.setSummary(((ComponentProfile) annotation).summary());
            } else if (DisplayOrder.class.isAssignableFrom(annotation.annotationType())) {
                displayOrder = Arrays.asList(((DisplayOrder) annotation).order());
            }
        }

        for (Field field : clazz.getDeclaredFields()) {
            if ((!Modifier.isStatic(field.getModifiers()))
                    && (field.getDeclaredAnnotation(Transient.class) == null)) { // if we're not transient
                ClassDescriptorProperty fieldProperty = new ClassDescriptorProperty();
                fieldProperty.setOrder(
                        displayOrder.contains(field.getName()) ? displayOrder.indexOf(field.getName()) + 1
                                : 999);
                fieldProperty.setAdvanced(false);
                fieldProperty.setClassName(field.getType().getName());
                fieldProperty.setType(field.getType().getSimpleName());
                fieldProperty.setName(field.getName());
                fieldProperty.setAutoPopulated(field.getDeclaredAnnotation(AutoPopulated.class) != null);
                fieldProperty.setNullAllowed(field.getDeclaredAnnotation(NotNull.class) != null);

                for (Annotation annotation : field.getDeclaredAnnotations()) {
                    if (AdvancedConfig.class.isAssignableFrom(annotation.annotationType())) {
                        fieldProperty.setAdvanced(true);
                    } else if (InputFieldDefault.class.isAssignableFrom(annotation.annotationType())) {
                        fieldProperty.setDefaultValue(((InputFieldDefault) annotation).value());
                    }
                }
                classDescriptor.getClassDescriptorProperties().add(fieldProperty);
            }
        }

        try (ScanResult result = new ClassGraph().enableAllInfo().blacklistPackages(FCS_BLACKLIST).scan()) {

            List<String> subclassNames = result.getSubclasses(className).getNames();

            for (String subclassName : subclassNames) {
                classDescriptor.getSubTypes().add(subclassName);
            }
        }

    } catch (ClassNotFoundException e) {
        throw new CoreException(e);
    }
    return new XStreamJsonMarshaller().marshal(classDescriptor);
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

@Override
public Object getTargetForField(Field field) {
    Acomponent ac = field.getDeclaredAnnotation(Acomponent.class);
    for (Object target : targets) {
        for (Field declaredField : target.getClass().getDeclaredFields()) {
            Acomponent ac1 = declaredField.getDeclaredAnnotation(Acomponent.class);
            try {
                if (ac.ref().equals(ac1.ref())) {
                    return target;
                }//  w  w  w.  j  a v a 2 s.c  om
            } catch (Exception e) {
                infoError(e);
            }
        }
    }
    throw new UnsupportedOperationException("No h nenhum <target> para o <field> [" + ac.ref() + "].");
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

private void mudarReferencia(Field field) {
    Acomponent ac = field.getDeclaredAnnotation(Acomponent.class);
    String ref = ac.ref();//from   w  w  w. java2  s.c  om
    if (ref.isEmpty()) {
        ref = field.getName().toLowerCase();
    }

    int i = 0;
    for (Field f : fields) {
        Acomponent ac2 = f.getDeclaredAnnotation(Acomponent.class);
        if (ac2.ref().contains(ref)) {
            i++;
        }
    }

    if (i > 0) {
        ref = String.format("%s_%d", ref, i);
    }
    changeAnnotationValue(ac, "ref", ref);
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

private void addField(Field field) {
    if (!fields.contains(field)) {
        Acomponent ac = field.getDeclaredAnnotation(Acomponent.class);
        LogServer.getInstance().debug(null, "Adicionando a Field: [{0}] ~> {1}", field.hashCode(), ac.ref());
        fields.add(field);//  ww  w  . ja  v  a2 s .c  om

        AbstractComponetAdapter adapter = getComponentAdapter(ac);
        LogServer.getInstance().debug(null, "agregando um <adapter> [{0}] para ~> {1}", adapter, ac.ref());
        adapters.put(field, adapter);

    } else {
        LogServer.getInstance().debug(null, "J contem a Field", field);
    }
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

public Field getField(String ref) {
    for (Field field : fields) {
        if (field.isAnnotationPresent(Acomponent.class)) {
            Acomponent ac = field.getDeclaredAnnotation(Acomponent.class);
            if (ac.ref().equalsIgnoreCase(ref)) {
                return field;
            }//from  www . jav  a2 s.co  m
        }
    }

    throw new UnsupportedOperationException("Field not found!");
}