Example usage for java.lang Class getAnnotations

List of usage examples for java.lang Class getAnnotations

Introduction

In this page you can find the example usage for java.lang Class getAnnotations.

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:main.okapi.cf.annotations.AnnotationsInfo.java

public JSONObject getInfo() throws ClassNotFoundException, IOException, JSONException {
    JSONObject obj = new JSONObject();
    ArrayList<JSONObject> cl = new ArrayList<JSONObject>();
    Iterable<Class> classes = getClasses(this.topPackage);
    for (Class c : classes) {
        JSONObject forClass = new JSONObject();
        if (c.getAnnotations().length > 0) {

            ArrayList<JSONObject> parameters = new ArrayList<JSONObject>();
            for (Field field : c.getDeclaredFields()) {
                if (field.isAnnotationPresent(HyperParameter.class)) {
                    HyperParameter hp = field.getAnnotation(HyperParameter.class);
                    JSONObject parJSON = new JSONObject();
                    parJSON.put("parameterName", hp.parameterName());
                    parJSON.put("defaultValue", hp.defaultValue());
                    parJSON.put("minimumValue", hp.minimumValue());
                    parJSON.put("maximumValue", hp.maximumValue());
                    parameters.add(parJSON);
                }/*from  ww w.  ja v  a 2s .  c o m*/
            }
            JSONObject method = new JSONObject();
            method.put("hyperParameters", parameters);
            method.put("class", c.getCanonicalName());
            cl.add(method);
        }
    }
    obj.put("methods", cl);
    return obj;
}

From source file:ch.aonyx.broker.ib.api.util.AnnotationUtils.java

/**
 * Find a single {@link Annotation} of <code>annotationType</code> from the supplied {@link Class}, traversing its
 * interfaces and superclasses if no annotation can be found on the given class itself.
 * <p>//from  w w w  . j av a  2 s .co  m
 * This method explicitly handles class-level annotations which are not declared as
 * {@link java.lang.annotation.Inherited inherited} <i>as well as annotations on interfaces</i>.
 * <p>
 * The algorithm operates as follows: Searches for an annotation on the given class and returns it if found. Else
 * searches all interfaces that the given class declares, returning the annotation from the first matching
 * candidate, if any. Else proceeds with introspection of the superclass of the given class, checking the superclass
 * itself; if no annotation found there, proceeds with the interfaces that the superclass declares. Recursing up
 * through the entire superclass hierarchy if no match is found.
 * 
 * @param clazz
 *            the class to look for annotations on
 * @param annotationType
 *            the annotation class to look for
 * @return A tuple {@link Pair} containing the annotation on the left hand side and the class on the right hand side
 *         or <code>null</code> if none found
 */
public static <A extends Annotation> Pair<A, Class<?>> findAnnotation(final Class<?> clazz,
        final Class<A> annotationType) {
    Validate.notNull(clazz, "Class must not be null");
    A annotation = clazz.getAnnotation(annotationType);
    if (annotation != null) {
        return new ImmutablePair<A, Class<?>>(annotation, clazz);
    }
    for (final Class<?> ifc : clazz.getInterfaces()) {
        final Pair<A, Class<?>> pair = findAnnotation(ifc, annotationType);
        if (pair != null) {
            annotation = pair.getLeft();
            if (annotation != null) {
                return new ImmutablePair<A, Class<?>>(annotation, ifc);
            }
        }
    }
    if (!Annotation.class.isAssignableFrom(clazz)) {
        for (final Annotation ann : clazz.getAnnotations()) {
            final Pair<A, Class<?>> pair = findAnnotation(ann.annotationType(), annotationType);
            if (pair != null) {
                annotation = pair.getLeft();
                if (annotation != null) {
                    return new ImmutablePair<A, Class<?>>(annotation, ann.annotationType());
                }
            }
        }
    }
    final Class<?> superClass = clazz.getSuperclass();
    if ((superClass == null) || (superClass == Object.class)) {
        return null;
    }
    return findAnnotation(superClass, annotationType);
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.entity.def.DefaultEntityResolver.java

/** {@inheritDoc} */
@Override//from ww  w  . j a  v a2  s. co  m
public DescribedEntity<?> resolveEntity(final Class<?> entityType) {
    DefaultEntityResolver.LOGGER.debug("Resolving entity {}", entityType);
    Validate.notNull(entityType, "Entity type may not be null.");
    @SuppressWarnings("unchecked")
    final EntityBuilder<?> builder = DescribedEntity.createBuilder().entityType((Class<Object>) entityType);
    final List<Class<?>> hierarchy = new LinkedList<Class<?>>();
    if (this.searchHierarchyResolver) {
        final Deque<Class<?>> types = new LinkedList<Class<?>>();
        final Set<Class<?>> processed = new HashSet<Class<?>>();
        types.add(entityType);
        while (!types.isEmpty()) {
            final Class<?> next = types.pop();
            hierarchy.add(next);
            final Class<?> superType = next.getSuperclass();
            if (!CheckUtil.isNull(superType) && !processed.contains(superType)) {
                types.add(superType);
            }
            for (final Class<?> interfaceType : next.getInterfaces()) {
                if (!processed.contains(interfaceType)) {
                    types.add(interfaceType);
                }
            }
            processed.add(next);
        }
    } else {
        hierarchy.add(entityType);
    }
    for (final Class<?> type : hierarchy) {
        for (final Annotation a : type.getAnnotations()) {
            builder.addAnnotation(a);
        }
    }
    final DescribedEntity<?> result = builder.build();
    DefaultEntityResolver.LOGGER.debug("Resolved entity {} for type {}", result, entityType);
    return result;
}

From source file:org.chorusbdd.chorus.interpreter.interpreter.SpringContextSupport.java

/**
 * Will load a Spring context from the named @ContextConfiguration resource. Will then inject the beans
 * into fields annotated with @Resource where the name of the bean matches the name of the field.
 *
 * @param handler an instance of the handler class that will be used for testing
 *//*  ww  w  .j  a  va  2 s.c om*/
void injectSpringResources(Object handler, FeatureToken featureToken) throws Exception {
    log.trace("Looking for SpringContext annotation on handler " + handler);
    Class<?> handlerClass = handler.getClass();
    Annotation[] annotations = handlerClass.getAnnotations();
    String contextFileName = findSpringContextFileName(handler, annotations);
    if (contextFileName != null) {
        log.debug(
                "Found SpringContext annotation with value " + contextFileName + " will inject spring context");
        springInjector.injectSpringContext(handler, featureToken, contextFileName);
    }
}

From source file:org.apache.openaz.pepapi.std.StdObligationHandlerRegistry.java

/**
 * Process Annotations in the classes provided and translate those into <code>ObligationCriteria</code>.
 *
 * @param oHandlerClass//  ww w.j  ava 2s  .  c  o  m
 * @return an ObligationCriteria instance.
 */
private ObligationCriteria processAnnotation(Class<?> oHandlerClass) {
    ObligationCriteria criteria = null;
    for (Annotation a : oHandlerClass.getAnnotations()) {
        if (a.annotationType().equals(MatchAnyObligation.class)) {
            String[] obligationIds = ((MatchAnyObligation) a).value();
            ObligationCriteriaBuilder criteriaBuilder = new ObligationCriteriaBuilder();
            if (obligationIds != null && obligationIds.length > 0) {
                criteriaBuilder.matchAnyObligationId(obligationIds);
            } else {
                criteriaBuilder.matchAnyObligation();
            }
            criteria = criteriaBuilder.build();
        } else if (a.annotationType().equals(MatchAllObligationAttributes.class)) {
            ObligationCriteriaBuilder criteriaBuilder = new ObligationCriteriaBuilder();
            MatchAllObligationAttributes attributeObligationAnnotation = (MatchAllObligationAttributes) a;
            for (Attribute attribute : attributeObligationAnnotation.value()) {
                String attributeId = attribute.id();
                String[] anyValue = attribute.anyValue();
                if (anyValue != null && anyValue.length > 0) {
                    criteriaBuilder.matchAttributeWithAnyGivenValue(attributeId, anyValue);
                } else {
                    criteriaBuilder.matchAttribute(attributeId);
                }
            }
            criteria = criteriaBuilder.build();
        }
    }
    return criteria;
}

From source file:org.pmp.budgeto.app.SwaggerDispatcherConfigTest.java

@Test
public void springConf() throws Exception {

    Class<?> clazz = swaggerDispatcherConfig.getClass();
    Assertions.assertThat(clazz.getAnnotations()).hasSize(4);
    Assertions.assertThat(clazz.isAnnotationPresent(Configuration.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableWebMvc.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableSwagger.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(ComponentScan.class)).isTrue();
    Assertions.assertThat(clazz.getAnnotation(ComponentScan.class).basePackages())
            .containsExactly("com.ak.swaggerspringmvc.shared.app", "com.ak.spring3.music");

    Field fSpringSwaggerConfig = clazz.getDeclaredField("springSwaggerConfig");
    Assertions.assertThat(fSpringSwaggerConfig.getAnnotations()).hasSize(1);
    Assertions.assertThat(fSpringSwaggerConfig.isAnnotationPresent(Autowired.class)).isTrue();

    Method mCustomImplementation = clazz.getDeclaredMethod("customImplementation", new Class[] {});
    Assertions.assertThat(mCustomImplementation.getAnnotations()).hasSize(1);
    Assertions.assertThat(mCustomImplementation.getAnnotation(Bean.class)).isNotNull();
}

From source file:org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport.java

/**
 * Determines the qualifiers of the given type.
 *///from ww  w. j av a  2s.c o m
@SuppressWarnings("serial")
private Set<Annotation> getQualifiers(final Class<?> type) {

    Set<Annotation> qualifiers = new HashSet<Annotation>();
    Annotation[] annotations = type.getAnnotations();
    for (Annotation annotation : annotations) {
        Class<? extends Annotation> annotationType = annotation.annotationType();
        if (annotationType.isAnnotationPresent(Qualifier.class)) {
            qualifiers.add(annotation);
        }
    }
    // Add @Default qualifier if no qualifier is specified.
    if (qualifiers.isEmpty()) {
        qualifiers.add(new AnnotationLiteral<Default>() {
        });
    }
    // Add @Any qualifier.
    qualifiers.add(new AnnotationLiteral<Any>() {
    });
    return qualifiers;
}

From source file:com.rosenvold.spring.SpringContextAnalyzer.java

boolean isComponent(Class clazz) {
    final Annotation[] annotations = clazz.getAnnotations();
    return containsAnnotation(annotations, Component.class);
}

From source file:org.seasar.karrta.jcr.register.JcrNodeComponentAutoRegister.java

@Override
@SuppressWarnings("unchecked")
public void processClass(final String packageName, final String shortClassName) {
    if (isIgnore(packageName, shortClassName))
        return;/*  www.  ja va2  s .  c  om*/

    for (int i = 0; i < getClassPatternSize(); ++i) {
        final ClassPattern cp = getClassPattern(i);
        if (cp.isAppliedPackageName(packageName) && cp.isAppliedShortClassName(shortClassName)) {
            try {
                Class clazz = Class.forName(ClassUtil.concatName(packageName, shortClassName));

                boolean hasNodeAnnotation = false;
                Annotation[] annotations = clazz.getAnnotations();
                for (Annotation a : annotations) {
                    if (a instanceof Node) {
                        hasNodeAnnotation = true;
                        break;
                    }
                }
                if (!hasNodeAnnotation)
                    continue;

                this.register(ClassUtil.concatName(packageName, shortClassName));
                this.jcrNodeClasses.add(clazz);
                logger_.debug("::: jcrNodeClass:[" + clazz.getName() + "]");

            } catch (ClassNotFoundException e) {
                throw new JcrRepositoryRuntimeException("", e);
            }
            return;
        }
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.config.CustomAnnotatorIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void defaultCustomAnnotatorIsNoop()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("annotationStyle", "none")); // turn off core annotations

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotations().length, is(0));
    assertThat(getter.getAnnotations().length, is(0));
}