下面列出了怎么用javax.lang.model.element.AnnotationMirror的API类实例代码及写法,或者点击链接到github查看源代码。
private void appendAnnotation(StringBuilder sb, AnnotationMirror annotationDesc, boolean topLevel) {
DeclaredType annotationType = annotationDesc.getAnnotationType();
if (annotationType != null && (!topLevel || isDocumented(annotationType))) {
appendType(sb, annotationType, false, false, true);
Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationDesc.getElementValues();
if (!values.isEmpty()) {
sb.append('('); //NOI18N
for (Iterator<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> it = values.entrySet().iterator(); it.hasNext();) {
Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> value = it.next();
createLink(sb, value.getKey(), value.getKey().getSimpleName());
sb.append('='); //NOI18N
appendAnnotationValue(sb, value.getValue());
if (it.hasNext())
sb.append(","); //NOI18N
}
sb.append(')'); //NOI18N
}
if (topLevel)
sb.append("<br>"); //NOI18N
}
}
@Override
public boolean refresh( TypeElement type ) {
List<? extends AnnotationMirror> allAnnotationMirrors =
getHelper().getCompilationController().getElements().
getAllAnnotationMirrors(type);
Map<String, ? extends AnnotationMirror> annotationsByType =
getHelper().getAnnotationsByType( allAnnotationMirrors );
boolean isStereotype = annotationsByType.get(
StereotypeChecker.STEREOTYPE) != null ;
if ( !isStereotype ){
return false;
}
boolean hasNamed = NamedStereotypeObjectProvider.hasNamed(type,
getHelper());
return hasNamed;
}
protected void setStereotypes( WebBeansModel model, Element element )
throws CdiException
{
if (getResult() != null) {
List<AnnotationMirror> stereotypes = getResult().getAllStereotypes(
element);
if (stereotypes.isEmpty()) {
getStereotypesComponent().setText("");
return;
}
StringBuilder text = new StringBuilder();
boolean isFqn = showFqns();
for (AnnotationMirror stereotype : stereotypes) {
appendAnnotationMirror(stereotype, text, isFqn);
}
getStereotypesComponent().setText(text.substring(0, text.length() - 2));
}
}
private static boolean isClassEjb31Bean(WorkingCopy wc, TypeElement srcClass) {
ClassPath cp = wc.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.COMPILE);
if (cp == null || cp.findResource("javax/ejb/embeddable/EJBContainer.class") == null) {
// if EJBContainer class is not available on classpath then it is not EJB 3.1
return false;
}
List<? extends AnnotationMirror> annotations = wc.getElements().getAllAnnotationMirrors(srcClass);
for (AnnotationMirror am : annotations) {
String annotation = ((TypeElement)am.getAnnotationType().asElement()).getQualifiedName().toString();
if (annotation.equals("javax.ejb.Singleton") || // NOI18N
annotation.equals("javax.ejb.Stateless") || // NOI18N
annotation.equals("javax.ejb.Stateful")) { // NOI18N
// class is an EJB
return true;
}
}
return false;
}
public static Set<TypeElement> getTypeElementsToProcess(Set<? extends Element> elements,
Set<? extends Element> supportedAnnotations) {
Set<TypeElement> typeElements = new HashSet<>();
for (Element element : elements) {
if (element instanceof TypeElement) {
boolean found = false;
for (Element subElement : element.getEnclosedElements()) {
for (AnnotationMirror mirror : subElement.getAnnotationMirrors()) {
for (Element annotation : supportedAnnotations) {
if (mirror.getAnnotationType().asElement().equals(annotation)) {
typeElements.add((TypeElement) element);
found = true;
break;
}
}
if (found) break;
}
if (found) break;
}
}
}
return typeElements;
}
private boolean isAbstract(final TypeElement annotationElement, final Element typeElement)
{
for (AnnotationMirror annotation : typeElement.getAnnotationMirrors())
{
if (annotation.getAnnotationType().asElement().equals(annotationElement))
{
Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues =
processingEnv.getElementUtils().getElementValuesWithDefaults(annotation);
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> element : annotationValues.entrySet())
{
if ("isAbstract".contentEquals(element.getKey().getSimpleName()))
{
return element.getValue().getValue().equals(Boolean.TRUE);
}
}
break;
}
}
return false;
}
/**
* return AnnotationMirror for first found annotation from annotationFqns
* @param element
* @param info
* @param annotationFqns
* @return
*/
public static AnnotationMirror getAnnotationMirror(Element element,
CompilationInfo info , String... annotationFqns)
{
Set<TypeElement> set = new HashSet<TypeElement>();
Elements els = info.getElements();
for( String annotation : annotationFqns){
TypeElement annotationElement = els.getTypeElement(
annotation);
if ( annotationElement != null ){
set.add( annotationElement );
}
}
List<? extends AnnotationMirror> annotations =
els.getAllAnnotationMirrors( element );
for (AnnotationMirror annotationMirror : annotations) {
Element declaredAnnotation = info.getTypes().asElement(
annotationMirror.getAnnotationType());
if ( set.contains( declaredAnnotation ) ){
return annotationMirror;
}
}
return null;
}
private static boolean containsAnnotatedJsfResource(CompilationController parameter) {
if (jsfResourcesElementHandles == null) {
loadJsfResourcesElementsHandles(parameter);
}
ClassIndex classIndex = parameter.getClasspathInfo().getClassIndex();
for (ElementHandle jsfResourceElementHandle : jsfResourcesElementHandles) {
Set<ElementHandle<TypeElement>> elements = classIndex.getElements(
jsfResourceElementHandle,
EnumSet.of(ClassIndex.SearchKind.TYPE_REFERENCES),
EnumSet.of(ClassIndex.SearchScope.SOURCE));
for (ElementHandle<TypeElement> handle : elements) {
TypeElement element = handle.resolve(parameter);
if (element != null) {
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (ElementHandle.create(annotationMirror.getAnnotationType().asElement())
.equals(jsfResourceElementHandle)) {
return true;
}
}
}
}
}
return false;
}
public void testScanAnnotationsOnFields() throws Exception {
final AnnotationModelHelper helper = AnnotationModelHelper.create(createClasspathInfoForScanningAnnotations());
final Set<String> elements = new HashSet<String>();
helper.runJavaSourceTask(new Callable<Void>() {
public Void call() throws InterruptedException {
helper.getAnnotationScanner().findAnnotations(
"javax.annotation.Resource",
EnumSet.of(ElementKind.FIELD),
new AnnotationHandler() {
public void handleAnnotation(TypeElement typeElement, Element element, AnnotationMirror annotationMirror) {
assertEquals("foo.MyClass", typeElement.getQualifiedName().toString());
elements.add(element.getSimpleName().toString());
}
});
return null;
}
});
assertEquals(1, elements.size());
assertTrue(elements.contains("myDS"));
}
public FieldSpec buildField() {
FieldSpec.Builder fieldSpec =
FieldSpec.builder(TypeName.get(mAnnotatedField.type), mAnnotatedField.name);
if (mAnnotatedField.annotationMirrors != null) {
for (AnnotationMirror annotationMirror :
mAnnotatedField.annotationMirrors) {
TypeElement annotationElement =
(TypeElement) annotationMirror.getAnnotationType().asElement();
if (annotationElement.getQualifiedName().contentEquals(Override.class.getName())) {
// Don't copy @Override if present, since we will be adding our own @Override in the
// implementation.
continue;
}
fieldSpec.addAnnotation(AnnotationSpec.get(annotationMirror));
}
}
return fieldSpec.build();
}
@Override
public InterceptorsResultImpl getInterceptors( Element element ) {
Collection<InterceptorObject> interceptors = getModel().
getInterceptorsManager().getObjects();
Set<TypeElement> result = new HashSet<TypeElement>();
Collection<AnnotationMirror> elementBindings = getInterceptorBindings(element);
Set<String> elementBindingsFqns = getAnnotationFqns(elementBindings);
for (InterceptorObject interceptor : interceptors) {
TypeElement typeElement = interceptor.getTypeElement();
if ( hasInterceptorBindings( typeElement , elementBindingsFqns )){
result.add(typeElement);
}
}
filterBindingsByMembers(elementBindings, result, TypeElement.class);
return getInterceptorsResult( element , result );
}
private static void checkDatasourceField(TypeElement typeElement, String name) {
List<VariableElement> elements = ElementFilter.fieldsIn(typeElement.getEnclosedElements());
VariableElement variableElement = elements.get(0);
assertTrue(variableElement.getSimpleName().contentEquals(name)); // field name
DeclaredType declaredType = (DeclaredType) variableElement.asType();
TypeElement returnTypeElement = (TypeElement) declaredType.asElement();
assertTrue(returnTypeElement.getQualifiedName().contentEquals("javax.sql.DataSource")); // field type
AnnotationMirror annotationMirror = variableElement.getAnnotationMirrors().get(0);
DeclaredType annotationDeclaredType = annotationMirror.getAnnotationType();
TypeElement annotationTypeElement = (TypeElement) annotationDeclaredType.asElement();
assertTrue(annotationTypeElement.getQualifiedName().contentEquals("javax.annotation.Resource")); // annotation type
Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry = annotationMirror.getElementValues().entrySet().iterator().next();
String attributeName = entry.getKey().getSimpleName().toString();
String attributeValue = (String) entry.getValue().getValue();
assertEquals("name", attributeName); // attributes
assertEquals(name, attributeValue);
}
private static void populateParam(CompilationController controller, VariableElement paramEl, ParamModel paramModel) {
paramModel.setParamType(paramEl.asType().toString());
TypeElement paramAnotationEl = controller.getElements().getTypeElement("javax.jws.WebParam"); //NOI18N
List<? extends AnnotationMirror> paramAnnotations = paramEl.getAnnotationMirrors();
for (AnnotationMirror anMirror : paramAnnotations) {
if (controller.getTypes().isSameType(paramAnotationEl.asType(), anMirror.getAnnotationType())) {
Map<? extends ExecutableElement, ? extends AnnotationValue> expressions = anMirror.getElementValues();
for(Entry<? extends ExecutableElement, ? extends AnnotationValue> entry:
expressions.entrySet())
{
ExecutableElement ex = entry.getKey();
AnnotationValue value = entry.getValue();
if (ex.getSimpleName().contentEquals("name")) { //NOI18N
paramModel.name = (String)value.getValue();
} else if (ex.getSimpleName().contentEquals("partName")) { //NOI18N
paramModel.setPartName((String)value.getValue());
} else if (ex.getSimpleName().contentEquals("targetNamespace")) { //NOI18N
paramModel.setTargetNamespace((String)value.getValue());
} else if (ex.getSimpleName().contentEquals("mode")) { //NOI18N
paramModel.setMode(Mode.valueOf(value.getValue().toString()));
}
}
}
}
}
private boolean useReflection(Element field) {
for (AnnotationMirror annotationMirror : field.getAnnotationMirrors()) {
if (STATE_REFLECTION_CLASS_NAME.equals(annotationMirror.getAnnotationType().toString())) {
return true;
}
}
return false;
}
private boolean isObservesParameter( VariableElement element,
ExecutableElement method , List<? extends AnnotationMirror> annotations )
throws org.netbeans.modules.web.beans.api.model.InjectionPointDefinitionError
{
List<? extends VariableElement> parameters = method.getParameters();
boolean observesFound = false;
for (VariableElement variableElement : parameters) {
if ( AnnotationObjectProvider.hasAnnotation(variableElement,
OBSERVES_ANNOTATION, getModel().getHelper()))
{
if ( observesFound ){
throw new org.netbeans.modules.web.beans.api.model.
InjectionPointDefinitionError(method,
NbBundle.getMessage(WebBeansModelImplementation.class,
"ERR_MultipleObserves" , method.getSimpleName()));
}
observesFound = true;
}
}
if ( !observesFound ){
return false;
}
String badAnnotation = checkInjectProducers(annotations);
if ( badAnnotation != null ){
throw new org.netbeans.modules.web.beans.api.model.
InjectionPointDefinitionError( method,
NbBundle.getMessage(WebBeansModelImplementation.class,
"ERR_ObserverHasInjectOrProduces" , method.getSimpleName(),
badAnnotation ));
}
return observesFound;
}
public boolean findTypeInAnnotation(AnnotationMirror imported, String string,
String className) {
Map<? extends ExecutableElement, ? extends AnnotationValue> values = imported
.getElementValues();
for (ExecutableElement element : values.keySet()) {
if (values.get(element).accept(typeFinder, null)) {
return true;
}
}
return false;
}
private Element getCandidateAnnotationElement(Set<Element> seen, AnnotationMirror annotation) {
Element element = annotation.getAnnotationType().asElement();
if (seen.contains(element)) {
return null;
}
// We need to visit all indexed annotations.
if (!isIndexedAnnotation(annotation)) {
seen.add(element);
}
return (!element.toString().startsWith("java.lang") ? element : null);
}
public static boolean hasFqn( AnnotationMirror mirror , String fqn){
Element anElement = mirror.getAnnotationType().asElement();
if ( anElement instanceof TypeElement ){
return fqn.contentEquals( ((TypeElement)anElement).getQualifiedName());
}
return false;
}
private boolean refresh(TypeElement typeElement) {
AnnotationParser parser = AnnotationParser.create(getHelper());
parser.expectString("name", AnnotationParser.defaultValue(typeElement.getSimpleName()));
List<? extends AnnotationMirror> annotations = typeElement.getAnnotationMirrors();
if (annotations.size() == 0) {
return false;
}
name = parser.parse(annotations.get(0)).get("name", String.class);
return true;
}
public List<T> createInitialObjects() throws InterruptedException {
final List<T> result = new ArrayList<T>();
helper.getAnnotationScanner().findAnnotations(annotationName, AnnotationScanner.TYPE_KINDS, new AnnotationHandler() {
public void handleAnnotation(TypeElement type, Element element, AnnotationMirror annotation) {
result.add(newItem(helper, type));
}
});
return result;
}
@Override
public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
if (delegate() != null) {
return delegate().getCompletions(element, annotation, member, userText);
} else {
return Collections.emptySet();
}
}
void filter( Set<T> set ) {
super.filter(set);
if ( set.size() == 0 ){
return;
}
/*
* Binding annotation could have members. See example :
* @BindingType
* @Retention(RUNTIME)
* @Target({METHOD, FIELD, PARAMETER, TYPE})
* public @interface PayBy {
* PaymentMethod value();
* @NonBinding String comment();
* }
* One need to check presence of member in binding annotation at
* injected point and compare this member with member in annotation
* for discovered type.
* Members with @Nonbinding annotation should be ignored.
*/
for (AnnotationMirror annotation : getBindingAnnotations()) {
Map<? extends ExecutableElement, ? extends AnnotationValue>
elementValues = annotation.getElementValues();
Set<ExecutableElement> bindingMembers = collectBindingMembers(
annotation , getImplementation() );
checkMembers(elementValues, bindingMembers, set );
}
}
public List<TypeElement> getTypesFromAnnotation(AnnotationMirror annotationMirror,
String fieldname) {
List<TypeElement> collected = new ArrayList<>();
if (annotationMirror != null) {
Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationMirror
.getElementValues();
for (ExecutableElement element : values.keySet()) {
if (element.getSimpleName().toString().equals(fieldname)) {
values.get(element).accept(typeCollector, collected);
}
}
}
return collected;
}
private static AnnotationMirror findAnnotationMirror(Element element, ProcessingEnvironment processingEnv, Class<? extends Annotation> annotation) {
for (AnnotationMirror ann : element.getAnnotationMirrors()) {
if (processingEnv.getElementUtils().getBinaryName((TypeElement) ann.getAnnotationType().asElement()).
contentEquals(annotation.getName())) {
return ann;
}
}
return null;
}
@Override
public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
for (AnnotationMirror annotationMirror :
elements.getAllAnnotationMirrors(e) ) {
Element e2 = annotationMirror.getAnnotationType().asElement();
p.add((TypeElement) e2);
}
return super.scan(e, p);
}
public boolean isDeprecated0(Element e) {
if (!utils.getDeprecatedTrees(e).isEmpty()) {
return true;
}
JavacTypes jctypes = ((DocEnvImpl)configuration.docEnv).toolEnv.typeutils;
TypeMirror deprecatedType = utils.getDeprecatedType();
for (AnnotationMirror anno : e.getAnnotationMirrors()) {
if (jctypes.isSameType(anno.getAnnotationType().asElement().asType(), deprecatedType))
return true;
}
return false;
}
public BasicImpl(AnnotationModelHelper helper, AnnotationMirror annotation, String name, Column column, String temporal) {
this.name = name;
this.column = column;
this.temporal = temporal;
AnnotationParser parser = AnnotationParser.create(helper);
parser.expectPrimitive("optional", Boolean.class, parser.defaultValue(true));
parseResult = parser.parse(annotation);
}
public static boolean isUnusableByJsSuppressed(AnnotatedConstruct binding) {
AnnotationMirror suppressWarningsBinding =
AnnotationUtils.findAnnotationBindingByName(
binding.getAnnotationMirrors(), SUPPRESS_WARNINGS_ANNOTATION_NAME);
if (suppressWarningsBinding == null) {
return false;
}
List<?> suppressions =
AnnotationUtils.getAnnotationParameterArray(suppressWarningsBinding, "value");
return suppressions.stream().map(Object::toString).anyMatch("\"unusable-by-js\""::equals);
}
private void addRegistrarInvokers(MethodSpec.Builder builder) {
addImportInvokers(builder, configurationType);
List<? extends AnnotationMirror> annotationMirrors = configurationType.getAnnotationMirrors();
for (AnnotationMirror am : annotationMirrors) {
// Looking up something like @EnableBar
TypeElement element = (TypeElement) am.getAnnotationType().asElement();
addImportInvokers(builder, element);
}
}
/**
* @param annotation an annotation instance (null permitted)
* @param name the name of an attribute of that annotation
* @return the corresponding value if found
*/
private AnnotationValue findAnnotationValue(AnnotationMirror annotation, String name) {
if (annotation != null) {
for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> entry : annotation.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().contentEquals(name)) {
return entry.getValue();
}
}
}
return null;
}