Java Code Examples for java.lang.annotation.Annotation#annotationType()

The following examples show how to use java.lang.annotation.Annotation#annotationType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainParser.java    From osmo with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void parseClass(ParserResult result, ParserParameters parameters, StringBuilder errors) {
  Class clazz = parameters.getModelClass();
  Annotation[] annotations = clazz.getAnnotations();
  for (Annotation annotation : annotations) {
    Class<? extends Annotation> annotationClass = annotation.annotationType();
    log.d("class annotation:" + annotationClass);
    AnnotationParser parser = annotationParsers.get(annotationClass);
    if (parser == null) {
      //unsupported annotation (e.g. for some completely different tool)
      continue;
    }
    log.d("parser:" + parser);
    //set the annotation itself as a parameter to the used parser object
    parameters.setAnnotation(annotation);
    //and finally parse it
    parser.parse(result, parameters, errors);
  }
}
 
Example 2
Source File: DefaultConfigNodeConverter.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected void validateAnnotationChange(Annotation annotation)
{
    Class<? extends Annotation> annotationType = annotation.annotationType();

    if (Folder.class.equals(annotationType) || View.class.equals(annotationType))
    {
        return;
    }

    ViewMetaData viewMetaData = annotationType.getAnnotation(ViewMetaData.class);
    if (viewMetaData == null)
    {
        return;
    }

    Aggregated aggregated = viewMetaData.annotationType().getAnnotation(Aggregated.class);
    if (aggregated != null && aggregated.value())
    {
        throw new IllegalStateException("it isn't supported to change aggregated meta-data," +
            "because inheritance won't work correctly");
    }
}
 
Example 3
Source File: AbstractWrapperBeanGenerator.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private void processXmlElement(List<Annotation> jaxb, String elemName, String elemNS, T type) {
    XmlElement elemAnn = null;
    for (Annotation a : jaxb) {
        if (a.annotationType() == XmlElement.class) {
            elemAnn = (XmlElement) a;
            jaxb.remove(a);
            break;
        }
    }
    String name = (elemAnn != null && !elemAnn.name().equals("##default"))
            ? elemAnn.name() : elemName;

    String ns = (elemAnn != null && !elemAnn.namespace().equals("##default"))
            ? elemAnn.namespace() : elemNS;

    boolean nillable = nav.isArray(type)
            || (elemAnn != null && elemAnn.nillable());

    boolean required = elemAnn != null && elemAnn.required();
    XmlElementHandler handler = new XmlElementHandler(name, ns, nillable, required);
    XmlElement elem = (XmlElement) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{XmlElement.class}, handler);
    jaxb.add(elem);
}
 
Example 4
Source File: AttributeMethods.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Check if values from the given annotation can be safely accessed without causing
 * any {@link TypeNotPresentException TypeNotPresentExceptions}. In particular,
 * this method is designed to cover Google App Engine's late arrival of such
 * exceptions for {@code Class} values (instead of the more typical early
 * {@code Class.getAnnotations() failure}.
 * @param annotation the annotation to validate
 * @throws IllegalStateException if a declared {@code Class} attribute could not be read
 * @see #isValid(Annotation)
 */
void validate(Annotation annotation) {
	assertAnnotation(annotation);
	for (int i = 0; i < size(); i++) {
		if (canThrowTypeNotPresentException(i)) {
			try {
				get(i).invoke(annotation);
			}
			catch (Throwable ex) {
				throw new IllegalStateException("Could not obtain annotation attribute value for " +
						get(i).getName() + " declared on " + annotation.annotationType(), ex);
			}
		}
	}
}
 
Example 5
Source File: MainParser.java    From osmo with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Parse the relevant annotated fields and pass these to correct {@link AnnotationParser} objects.
 *
 * @param result The parse results will be provided here.
 * @return A string listing all found errors.
 */
private void parseFields(ParserResult result, ParserParameters parameters, StringBuilder errors) {
  Object obj = parameters.getModel();
  //first we find all declared fields of any scope and type (private, protected, ...)
  Collection<Field> fields = getAllFields(obj.getClass());
  log.d("fields " + fields.size());
  //now we loop through all fields defined in the model object
  for (Field field : fields) {
    log.d("field:" + field);
    //set the field to be accessible from the parser objects
    parameters.setField(field);
    Annotation[] annotations = field.getAnnotations();
    parameters.setFieldAnnotations(annotations);
    //loop through all defined annotations for each field
    for (Annotation annotation : annotations) {
      Class<? extends Annotation> annotationClass = annotation.annotationType();
      log.d("field annotation:" + annotationClass);
      AnnotationParser parser = annotationParsers.get(annotationClass);
      if (parser == null) {
        //unsupported annotation (e.g. for some completely different tool)
        continue;
      }
      log.d("parser:" + parser);
      //set the annotation itself as a parameter to the used parser object
      parameters.setAnnotation(annotation);
      //and finally parse it
      parser.parse(result, parameters, errors);
    }
    //parse specific types of fields, without annotations (searchableinput)
    parseField(field, result, parameters, errors);
  }
}
 
Example 6
Source File: ScopeManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * For some class to be injected, return its scope (identified by a scope annotation) or <code>null</code> if the
 * type is not scoped.
 */
public static final Class<? extends Annotation> getScopeFromScopedClass(Class<?> clsToBeInjected) {
	Annotation match = null;
	for (Annotation ann : clsToBeInjected.getAnnotations()) {
		if (isScopeAnnotation(ann.annotationType())) {
			if (match != null) {
				// already have a match -> duplicates are not allowed
				throw new IllegalStateException(
						"class has several scope annotations: " + clsToBeInjected.getName());
			}
			match = ann;
		}
	}
	return match != null ? match.annotationType() : null;
}
 
Example 7
Source File: Secure.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static Set<String> getRolesAllowed(Map<Class<?>, Annotation> annotations) {

		Set<String> roles = U.set();

		for (Map.Entry<Class<?>, Annotation> e : annotations.entrySet()) {
			Annotation ann = e.getValue();
			Class<? extends Annotation> type = ann.annotationType();

			if (type.equals(Administrator.class)) {
				roles.add(Role.ADMINISTRATOR);
			} else if (type.equals(Manager.class)) {
				roles.add(Role.MANAGER);
			} else if (type.equals(Moderator.class)) {
				roles.add(Role.MODERATOR);
			} else if (type.equals(LoggedIn.class)) {
				roles.add(Role.LOGGED_IN);
			} else if (type.equals(Roles.class)) {
				String[] values = ((Roles) ann).value();
				U.must(values.length > 0, "At least one role must be specified in @Roles annotation!");
				for (String r : values) {
					roles.add(r.toLowerCase());
				}
			}
		}

		return roles;
	}
 
Example 8
Source File: TypeInfo.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Finds the specified annotation from the array and returns it.
 * Null if not found.
 */
public <A extends Annotation> A get( Class<A> annotationType ) {
    for (Annotation a : annotations) {
        if(a.annotationType()==annotationType)
            return annotationType.cast(a);
    }
    return null;
}
 
Example 9
Source File: TarsHelper.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean isHolder(Annotation[] annotations) {
    if (annotations == null || annotations.length < 0) {
        return false;
    }
    for (Annotation annotation : annotations) {
        if (annotation.annotationType() == TarsHolder.class) {
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: RuntimeInlineAnnotationReader.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public <A extends Annotation> A getMethodParameterAnnotation(Class<A> annotation, Method method, int paramIndex, Locatable srcPos) {
    Annotation[] pa = method.getParameterAnnotations()[paramIndex];
    for( Annotation a : pa ) {
        if(a.annotationType()==annotation)
            return LocatableAnnotation.create((A)a,srcPos);
    }
    return null;
}
 
Example 11
Source File: TypeDescriptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
@SuppressWarnings("unchecked")
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
	for (Annotation annotation : getAnnotations()) {
		if (annotation.annotationType() == annotationClass) {
			return (T) annotation;
		}
	}
	return null;
}
 
Example 12
Source File: Key.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the strategy for an annotation.
 */
static AnnotationStrategy strategyFor(Annotation annotation) {
    Objects.requireNonNull(annotation, "annotation");
    Class<? extends Annotation> annotationType = annotation.annotationType();
    ensureRetainedAtRuntime(annotationType);
    ensureIsBindingAnnotation(annotationType);

    if (annotationType.getMethods().length == 0) {
        return new AnnotationTypeStrategy(annotationType, annotation);
    }

    return new AnnotationInstanceStrategy(annotation);
}
 
Example 13
Source File: TransactionStrategyHelper.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the first CDI-Qualifier Annotation from the given annotations array
 */
private Class<? extends Annotation> getFirstQualifierAnnotation(Annotation[] annotations)
{
    for (Annotation ann : annotations)
    {
        if (beanManager.isQualifier(ann.annotationType()))
        {
            return ann.annotationType();
        }
    }

    return null;
}
 
Example 14
Source File: ReflectUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Derives whether the {@code i}th parameter of a method is optional. */
public static boolean isParameterOptional(Method method, int i) {
  for (Annotation annotation : method.getParameterAnnotations()[i]) {
    if (annotation.annotationType() == Parameter.class) {
      return ((Parameter) annotation).optional();
    }
  }
  return false;
}
 
Example 15
Source File: Reflection.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
static @Nullable <T extends Annotation> T findAnnotation(
    Annotation[] annotations, Class<T> annotationType) {
  for (Annotation annotation : annotations) {
    if (annotation.annotationType() == annotationType) {
      return annotationType.cast(annotation);
    }
  }
  return null;
}
 
Example 16
Source File: TypeUtil.java    From fastquery with Apache License 2.0 5 votes vote down vote up
/**
 * 处理 @Param 模板参数
 *
 * @param method 方法
 * @param args   给这个方法传递的参数值
 * @param sql    sql语句
 * @return sql
 */
static String paramFilter(MethodInfo method, Object[] args, String sql) {
    String s = sql.replace("::", ":");
    // 替换@Param
    Annotation[][] annotations = method.getParameterAnnotations();
    QueryByNamed queryByNamed = method.getQueryByNamed();
    int len = annotations.length;
    for (int i = 0; i < len; i++) {
        Annotation[] anns = annotations[i];
        for (Annotation ann : anns) {
            if (ann.annotationType() == Param.class) {
                Param param = (Param) ann;
                Object objx = args[i];
                objx = BeanUtil.parseList(objx);
                // 这里的replaceAll的先后顺序很重要
                // '{' 是正则语法的关键字,必须转义
                if (queryByNamed == null) {
                    String replacement = getReplacement(objx, param.defaultVal());
                    s = replaceAllEL(s, param.value(), replacement);
                }

                // 将 ":xx" 格式的 替换成 "?num"
                // 替换时必须加单词分界符(\\b),举例说明: sql中同时存在":ABCD",":A",
                // 不加单词分界符,":A"替换成"?num"后,会使":ABCD"变成":?numBCD"
                s = s.replaceAll(":" + param.value() + "\\b", "?" + (i + 1));
            }
        }
    }
    // 替换@Param End
    return s;
}
 
Example 17
Source File: XmlUtils.java    From tutorial-soap-spring-boot-cxf with MIT License 5 votes vote down vote up
public static <T> String getNamespaceUriFromJaxbClass(Class<T> jaxbClass) throws InternalBusinessException {
    for(Annotation annotation: jaxbClass.getPackage().getAnnotations()){
        if(annotation.annotationType() == XmlSchema.class){
            return ((XmlSchema)annotation).namespace();
        }
    }
    throw new InternalBusinessException("namespaceUri not found -> Is it really a JAXB-Class, thats used to call the method?");
}
 
Example 18
Source File: XmlUtils.java    From tutorial-soap-spring-boot-cxf with MIT License 5 votes vote down vote up
public static <T> String getXmlTagNameFromJaxbClass(Class<T> jaxbClass) {
	String xmlTagName = "";
    for(Annotation annotation: jaxbClass.getAnnotations()){
        if(annotation.annotationType() == XmlRootElement.class){
            xmlTagName = ((XmlRootElement)annotation).name();
            break;
        }
    }
    return xmlTagName;
}
 
Example 19
Source File: DiagramExporterImpl.java    From txtUML with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean isOfType(
		Class<? extends Annotation> annotationClass, Annotation annot) {
	return annot.annotationType() == annotationClass;
}
 
Example 20
Source File: UiParameterEnricher.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private Map<String, String> toConfig(final Annotation annotation, final String prefix) {
    if (GridLayout.class == annotation.annotationType()) {
        final GridLayout layout = GridLayout.class.cast(annotation);
        return Stream
                .of(layout.names())
                .flatMap(name -> Stream
                        .of(annotation.annotationType().getMethods())
                        .filter(m -> m.getDeclaringClass() == annotation.annotationType()
                                && !"names".equals(m.getName()))
                        .collect(toMap(m -> prefix + name + "::" + m.getName(),
                                m -> toString(annotation, m, invoke -> {
                                    if (invoke.getClass().isArray()) {
                                        final Class<?> component = invoke.getClass().getComponentType();
                                        if (!Annotation.class.isAssignableFrom(component)) {
                                            return null;
                                        }
                                        final int length = Array.getLength(invoke);
                                        if (length == 0) {
                                            return "";
                                        }
                                        final Collection<Method> mtds = Stream
                                                .of(component.getMethods())
                                                .filter(mtd -> mtd.getDeclaringClass() == component
                                                        && "value".equals(mtd.getName()))
                                                .collect(toList());
                                        final StringBuilder builder = new StringBuilder("");
                                        for (int i = 0; i < length; i++) {
                                            final Object annot = Array.get(invoke, i);
                                            mtds
                                                    .forEach(p -> builder
                                                            .append(toString(Annotation.class.cast(annot), p,
                                                                    o -> null)));
                                            if (i + 1 < length) {
                                                builder.append('|');
                                            }
                                        }
                                        return builder.toString();
                                    }
                                    return null;
                                })))
                        .entrySet()
                        .stream())
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    final Map<String, String> config = Stream
            .of(annotation.annotationType().getMethods())
            .filter(m -> m.getDeclaringClass() == annotation.annotationType())
            .collect(toMap(m -> prefix + m.getName(), m -> toString(annotation, m, invoke -> null)));
    return config.isEmpty() ? singletonMap(prefix.substring(0, prefix.length() - "::".length()), "true") : config;
}