Java Code Examples for java.lang.reflect.AnnotatedElement#getAnnotation()

The following examples show how to use java.lang.reflect.AnnotatedElement#getAnnotation() . 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: CSJacksonAnnotationIntrospector.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object findSerializer(Annotated a) {
    AnnotatedElement ae = a.getAnnotated();
    Url an = ae.getAnnotation(Url.class);
    if (an == null) {
        return null;
    }

    if (an.type() == String.class) {
        return new UriSerializer(an);
    } else if (an.type() == List.class) {
        return new UrisSerializer(an);
    }

    throw new UnsupportedOperationException("Unsupported type " + an.type());

}
 
Example 2
Source File: JPAEdmProperty.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private void addForeignKey(final Attribute<?, ?> jpaAttribute) throws ODataJPAModelException,
    ODataJPARuntimeException {

  AnnotatedElement annotatedElement = (AnnotatedElement) jpaAttribute.getJavaMember();
  joinColumnNames = null;
  if (annotatedElement == null) {
    return;
  }
  JoinColumn joinColumn = annotatedElement.getAnnotation(JoinColumn.class);
  if (joinColumn == null) {
    JoinColumns joinColumns = annotatedElement.getAnnotation(JoinColumns.class);
    if (joinColumns != null) {
      for (JoinColumn jc : joinColumns.value()) {
        buildForeignKey(jc, jpaAttribute);
      }
    }
  } else {
    buildForeignKey(joinColumn, jpaAttribute);
  }
}
 
Example 3
Source File: AnnotationUtils.java    From dolphin with Apache License 2.0 6 votes vote down vote up
/**
 * Get a single {@link Annotation} of {@code annotationType} from the supplied
 * Method, Constructor or Field. Meta-annotations will be searched if the annotation
 * is not declared locally on the supplied element.
 * @param annotatedElement the Method, Constructor or Field from which to get the annotation
 * @param annotationType the annotation type to look for, both locally and as a meta-annotation
 * @return the matching annotation, or {@code null} if none found
 * @since 3.1
 */
public static <T extends Annotation> T getAnnotation(AnnotatedElement annotatedElement, Class<T> annotationType) {
	try {
		T ann = annotatedElement.getAnnotation(annotationType);
		if (ann == null) {
			for (Annotation metaAnn : annotatedElement.getAnnotations()) {
				ann = metaAnn.annotationType().getAnnotation(annotationType);
				if (ann != null) {
					break;
				}
			}
		}
		return ann;
	}
	catch (Exception ex) {
		// Assuming nested Class values not resolvable within annotation attributes...
		logIntrospectionFailure(annotatedElement, ex);
		return null;
	}
}
 
Example 4
Source File: AggregationFromAnnotationsParser.java    From presto with Apache License 2.0 6 votes vote down vote up
private static List<String> getNames(@Nullable AnnotatedElement outputFunction, AggregationFunction aggregationAnnotation)
{
    List<String> defaultNames = ImmutableList.<String>builder().add(aggregationAnnotation.value()).addAll(Arrays.asList(aggregationAnnotation.alias())).build();

    if (outputFunction == null) {
        return defaultNames;
    }

    AggregationFunction annotation = outputFunction.getAnnotation(AggregationFunction.class);
    if (annotation == null) {
        return defaultNames;
    }
    else {
        return ImmutableList.<String>builder().add(annotation.value()).addAll(Arrays.asList(annotation.alias())).build();
    }
}
 
Example 5
Source File: CreoleAnnotationHandler.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Given a single-argument method whose parameter is a {@link Collection}, use
 * the method's generic type information to determine the collection element
 * type and store it as the ITEM_CLASS_NAME attribute of the given Element.
 * 
 * @param method
 *          the setter method
 * @param paramElt
 *          the PARAMETER element
 */
private void determineCollectionElementType(AnnotatedElement method,
    Type paramType, Element paramElt) {
  if(paramElt.getAttributeValue("ITEM_CLASS_NAME") == null) {
    Class<?> elementType;
    CreoleParameter paramAnnot = method.getAnnotation(CreoleParameter.class);
    if(paramAnnot != null
        && paramAnnot.collectionElementType() != CreoleParameter.NoElementType.class) {
      elementType = paramAnnot.collectionElementType();
    } else {
      elementType = findCollectionElementType(paramType);
    }
    if(elementType != null) {
      paramElt.setAttribute("ITEM_CLASS_NAME", elementType.getName());
    }
  }
}
 
Example 6
Source File: PrintAnnotation.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
static Annotation getAnnotation(AnnotatedElement element, String annotationTypeName) {
    Class<?> annotationType = null; // Unbounded type token
    try {
        annotationType = Class.forName(annotationTypeName);
    } catch (Exception ex) {
        throw new IllegalArgumentException(ex);
    }
    return element.getAnnotation(annotationType.asSubclass(Annotation.class));
}
 
Example 7
Source File: GraphQLSchemaBuilder.java    From graphql-jpa with MIT License 5 votes vote down vote up
private String getSchemaDocumentation(AnnotatedElement annotatedElement) {
    if (annotatedElement != null) {
        SchemaDocumentation schemaDocumentation = annotatedElement.getAnnotation(SchemaDocumentation.class);
        return schemaDocumentation != null ? schemaDocumentation.value() : null;
    }

    return null;
}
 
Example 8
Source File: Ejb3TransactionAnnotationParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
	javax.ejb.TransactionAttribute ann = element.getAnnotation(javax.ejb.TransactionAttribute.class);
	if (ann != null) {
		return parseTransactionAnnotation(ann);
	}
	else {
		return null;
	}
}
 
Example 9
Source File: CommonAnnotationBeanPostProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public WebServiceRefElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) {
	super(member, pd);
	WebServiceRef resource = ae.getAnnotation(WebServiceRef.class);
	String resourceName = resource.name();
	Class<?> resourceType = resource.type();
	this.isDefaultName = !StringUtils.hasLength(resourceName);
	if (this.isDefaultName) {
		resourceName = this.member.getName();
		if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) {
			resourceName = Introspector.decapitalize(resourceName.substring(3));
		}
	}
	if (resourceType != null && Object.class != resourceType) {
		checkResourceType(resourceType);
	}
	else {
		// No resource type specified... check field/method.
		resourceType = getResourceType();
	}
	this.name = resourceName;
	this.elementType = resourceType;
	if (Service.class.isAssignableFrom(resourceType)) {
		this.lookupType = resourceType;
	}
	else {
		this.lookupType = resource.value();
	}
	this.mappedName = resource.mappedName();
	this.wsdlLocation = resource.wsdlLocation();
}
 
Example 10
Source File: EmptyValueLabel.java    From onedev with MIT License 5 votes vote down vote up
private static String getNameOfEmptyValue(AnnotatedElement element) {
	NameOfEmptyValue nameOfEmptyValue = element.getAnnotation(NameOfEmptyValue.class);
	if (nameOfEmptyValue != null)
		return HtmlEscape.escapeHtml5(nameOfEmptyValue.value());
	else
		return "Not defined";
}
 
Example 11
Source File: EditableUtils.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Get description of specified element from description parameter of {@link Editable} annotation
 *
 * @param element
 * 			annotated element to get description from
 * @return
 * 			defined description, or <tt>null</tt> if description can not be found
 */
public static @Nullable String getDescription(AnnotatedElement element) {
	Editable editable = element.getAnnotation(Editable.class);
	if (editable != null) {
		if (editable.description().length() != 0)
			return editable.description();
	}
	return null;
}
 
Example 12
Source File: AnnotationProcessingTaskFactory.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void attachValidationAction(PropertyAnnotationHandler handler, PropertyInfo propertyInfo, String fieldName) {
    final Method method = propertyInfo.method;
    Class<? extends Annotation> annotationType = handler.getAnnotationType();

    AnnotatedElement annotationTarget = null;
    if (method.getAnnotation(annotationType) != null) {
        annotationTarget = method;
    } else {
        try {
            Field field = method.getDeclaringClass().getDeclaredField(fieldName);
            if (field.getAnnotation(annotationType) != null) {
                annotationTarget = field;
            }
        } catch (NoSuchFieldException e) {
            // ok - ignore
        }
    }
    if (annotationTarget == null) {
        return;
    }

    Annotation optional = annotationTarget.getAnnotation(org.gradle.api.tasks.Optional.class);
    if (optional == null) {
        propertyInfo.setNotNullValidator(notNullValidator);
    }

    propertyInfo.attachActions(handler);
}
 
Example 13
Source File: PropertyAccessMixedImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static AccessType getAccessTypeOrNull(AnnotatedElement element) {
	if ( element == null ) {
		return null;
	}
	Access elementAccess = element.getAnnotation( Access.class );
	return elementAccess == null ? null : elementAccess.value();
}
 
Example 14
Source File: ResourcePathInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
@Override
public Object getValue(@NotNull Object adaptable, String name, @NotNull Type declaredType, @NotNull AnnotatedElement element,
        @NotNull DisposalCallbackRegistry callbackRegistry) {
    String[] resourcePaths = null;
    Path pathAnnotation = element.getAnnotation(Path.class);
    ResourcePath resourcePathAnnotation = element.getAnnotation(ResourcePath.class);
    if (pathAnnotation != null) {
        resourcePaths = getPathsFromAnnotation(pathAnnotation);
    } else if (resourcePathAnnotation != null) {
        resourcePaths = getPathsFromAnnotation(resourcePathAnnotation);
    }
    if (ArrayUtils.isEmpty(resourcePaths) && name != null) {
        // try the valuemap
        ValueMap map = getValueMap(adaptable);
        if (map != null) {
            resourcePaths = map.get(name, String[].class);
        }
    }
    if (ArrayUtils.isEmpty(resourcePaths)) {
        // could not find a path to inject
        return null;
    }

    ResourceResolver resolver = getResourceResolver(adaptable);
    if (resolver == null) {
        return null;
    }
    List<Resource> resources = getResources(resolver, resourcePaths, name);

    if (resources == null || resources.isEmpty()) {
        return null;
    }
    // unwrap/wrap if necessary
    if (isDeclaredTypeCollection(declaredType)) {
        return resources;
    } if (declaredType instanceof Class<?> && ((Class<?>)declaredType).isArray()){
        return resources.toArray(new Resource[0]);
    }
     if (resources.size() == 1) {
        return resources.get(0);
    } else {
        // multiple resources to inject, but field is not a list
        LOG.warn("Cannot inject multiple resources into field {} since it is not declared as a list", name);
        return null;
    }

}
 
Example 15
Source File: Matchers.java    From businessworks with Apache License 2.0 4 votes vote down vote up
public boolean matches(AnnotatedElement element) {
  Annotation fromElement = element.getAnnotation(annotation.annotationType());
  return fromElement != null && annotation.equals(fromElement);
}
 
Example 16
Source File: JPAEdmReferentialConstraintRole.java    From cloud-odata-java with Apache License 2.0 4 votes vote down vote up
private void extractJoinColumns() {
  /*
   * Check against Static Buffer whether the join column was already
   * extracted.
   */
  if (!jpaAttribute.equals(bufferedJPAAttribute)) {
    bufferedJPAAttribute = jpaAttribute;
    bufferedJoinColumns.clear();
  } else if (bufferedJoinColumns.isEmpty()) {
    roleExists = false;
    return;
  } else {
    roleExists = true;
    return;
  }

  AnnotatedElement annotatedElement = (AnnotatedElement) jpaAttribute
      .getJavaMember();

  if (annotatedElement == null) {
    return;
  }

  JoinColumn joinColumn = annotatedElement
      .getAnnotation(JoinColumn.class);
  if (joinColumn == null) {
    JoinColumns joinColumns = annotatedElement
        .getAnnotation(JoinColumns.class);

    if (joinColumns != null) {
      JoinColumn[] joinColumnArray = joinColumns.value();

      for (JoinColumn element : joinColumnArray) {
        bufferedJoinColumns.add(element);
      }
    } else {
      return;
    }
  } else {
    bufferedJoinColumns.add(joinColumn);
  }
  roleExists = true;
}
 
Example 17
Source File: Matchers.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(AnnotatedElement element) {
    return element.getAnnotation(annotationType) != null;
}
 
Example 18
Source File: AnnotationUtils.java    From simple-robot-core with Apache License 2.0 4 votes vote down vote up
/**
 * 从某个类上获取注解对象,注解可以深度递归
 * 如果存在多个继承注解,则优先获取浅层第一个注解,如果浅层不存在,则返回第一个获取到的注解
 * 请尽可能保证仅存在一个或者一种继承注解,否则获取到的类型将不可控
 *
 * @param from           获取注解的某个类
 * @param annotationType 想要获取的注解类型
 * @param ignored        获取注解列表的时候的忽略列表
 * @return 获取到的第一个注解对象
 */
public static <T extends Annotation> T getAnnotation(AnnotatedElement from, Class<T> annotationType, Class<T>... ignored) {
    // 首先尝试获取缓存
    T cache = getCache(from, annotationType);
    if(cache != null){
        return cache;
    }

    if(isNull(from, annotationType)){
        return null;
    }


    //先尝试直接获取
    T annotation = from.getAnnotation(annotationType);

    //如果存在直接返回,否则查询
    if (annotation != null) {
        saveCache(from, annotation);
        return annotation;
    }

    // 获取target注解
    Target target = annotationType.getAnnotation(Target.class);
    // 判断这个注解能否标注在其他注解上,如果不能,则不再深入获取
    boolean annotationable = false;
    if (target != null) {
        for (ElementType elType : target.value()) {
            if (elType == ElementType.TYPE || elType == ElementType.ANNOTATION_TYPE) {
                annotationable = true;
                break;
            }
        }
    }

    Annotation[] annotations = from.getAnnotations();
    annotation = annotationable ? getAnnotationFromArrays(annotations, annotationType, ignored) : null;


    // 如果还是获取不到,看看查询的注解类型有没有对应的ByNameType
    if (annotation == null) {
        annotation = getByNameAnnotation(from, annotationType);
    }

    // 如果无法通过注解本身所指向的byName注解获取,看看有没有反向指向此类型的注解
    // 此情况下不进行深层获取
    if(annotation == null){
        annotation = getAnnotationFromByNames(annotations, annotationType);
    }

    // 如果最终不是null,计入缓存
    if(annotation != null){
        saveCache(from, annotation);
    }else{
        nullCache(from, annotationType);
    }

    return annotation;
}
 
Example 19
Source File: GeneratorUtils.java    From spring-openapi with MIT License 4 votes vote down vote up
public static boolean shouldBeIgnored(AnnotatedElement annotatedElement) {
	return annotatedElement.getAnnotation(OpenApiIgnore.class) != null;
}
 
Example 20
Source File: EditableUtils.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Get icon of specified element from icon parameter of {@link Editable} annotation.
 *
 * @param element
 * 			annotated element to get icon from
 * @return
 * 			icon name of specified element, or <tt>null</tt> if not defined
 */
public static @Nullable String getIcon(AnnotatedElement element) {
	Editable editable = element.getAnnotation(Editable.class);
	if (editable != null && editable.icon().trim().length() != 0)
		return editable.icon();
	else
		return null;
}