下面列出了怎么用javax.annotation.processing.RoundEnvironment的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (CollectionUtils.isEmpty(set)) {
return false;
}
for (TypeElement typeElement : set) {
Set<? extends Element> annotated = roundEnvironment.getElementsAnnotatedWith(typeElement);
for (Element apiImplElement : annotated) {
ApiImpl annotation = apiImplElement.getAnnotation(ApiImpl.class);
if (annotation == null || !(apiImplElement instanceof TypeElement)) {
continue;
}
ApiContract<ClassName> apiNameContract = getApiClassNameContract((TypeElement) apiImplElement);
try {
JavaFile.builder(ApiConstants.PACKAGE_NAME_CONTRACT, buildClass(apiNameContract))
.build()
.writeTo(filer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (round++ == 0) {
try (Writer out = processingEnv.getFiler()
.createSourceFile("Anno.java")
.openWriter()) {
String target = processingEnv.getOptions().get("target");
String code = "import java.lang.annotation.ElementType;\n" +
"import java.lang.annotation.Target;\n" +
"@Target(ElementType." + target + ")\n" +
"@interface Anno { public String value(); }\n";
out.write(code);
} catch (IOException exc) {
throw new IllegalStateException(exc);
}
}
return true;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element annotatedElt : roundEnv.getElementsAnnotatedWith(CodeTranslate.class)) {
ExecutableElement methodElt = (ExecutableElement) annotatedElt;
TypeElement typeElt = (TypeElement) methodElt.getEnclosingElement();
if (typeElt.getQualifiedName().toString().equals(fqn) && methodElt.getSimpleName().toString().equals(method)) {
for (Lang lang : langs) {
Result result;
try {
String translation = translator.translate(methodElt, false, lang, RenderMode.SNIPPET);
result = new Result.Source(translation);
} catch (Exception e) {
result = new Result.Failure(e);
}
results.put(lang, result);
}
}
}
return false;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<String> packages = new TreeSet<>();
for (Element elem : roundEnv.getElementsAnnotatedWith(Service.class)) {
packages.add(elem.getEnclosingElement().toString());
}
if (!packages.isEmpty()) {
if (!hasRun) {
hasRun = true;
// Add the Karaf embedded package
try (PrintWriter w = appendResource("META-INF/org.apache.karaf.boot.bnd")) {
w.println("Karaf-Commands: " + String.join(",", packages));
} catch (Exception e) {
processingEnv.getMessager().printMessage(Kind.ERROR, "Error writing to META-INF/org.apache.karaf.boot.bnd: " + e.getMessage());
}
}
}
return true;
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (CollectionUtils.isNotEmpty(set)) {
try {
logger.info(">>> Found autowired field, start... <<<");
categories(roundEnvironment.getElementsAnnotatedWith(Autowired.class));
generateHelper();
} catch (Exception e) {
logger.error(e);
}
return true;
}
return false;
}
private void createFactoriesForClassesAnnotatedWithInjectConstructor(RoundEnvironment roundEnv) {
for (Element annotatedElement :
ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(InjectConstructor.class))) {
TypeElement annotatedTypeElement = (TypeElement) annotatedElement;
List<ExecutableElement> constructorElements =
ElementFilter.constructorsIn(annotatedTypeElement.getEnclosedElements());
if (constructorElements.size() != 1
|| constructorElements.get(0).getAnnotation(Inject.class) != null) {
error(
constructorElements.get(0),
"Class %s is annotated with @InjectInjectConstructor. Therefore, It must have one unique constructor and it should not be annotated with @Inject.",
annotatedTypeElement.getQualifiedName());
}
processInjectAnnotatedConstructor(
constructorElements.get(0), mapTypeElementToConstructorInjectionTarget);
}
}
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) {
TypeElement testMe = elements.getTypeElement(TestMe.class.getName());
Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe);
try {
for (Element sup : supers) {
Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter();
sub.write(String.format("class %s_GENERATED extends %s {}",
sup.getSimpleName(),
((TypeElement)sup).getQualifiedName()));
sub.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return true;
}
private void updateCommandSpecFromCommandAnnotation(CommandSpec result,
Element element,
Context context,
RoundEnvironment roundEnv) {
Command cmd = element.getAnnotation(Command.class);
if (cmd != null) {
updateCommandAttributes(result, cmd);
List<CommandSpec> subcommands = findSubcommands(element.getAnnotationMirrors(), context, roundEnv);
for (CommandSpec sub : subcommands) {
result.addSubcommand(sub.name(), sub);
}
if (cmd.mixinStandardHelpOptions()) {
context.commandsRequestingStandardHelpOptions.add(result);
}
}
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) {
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(Retain.class);
if (elements.isEmpty()) {
return true;
}
//TODO: verify activity implements onFirstCreate
verifyFieldsAccessible(elements);
log("processing " + elements.size() + " fields");
Element hostActivity = elements.iterator().next().getEnclosingElement();
TypeElement activityType = findAndroidActivitySuperType((TypeElement) hostActivity);
if (activityType == null) {
throw new IllegalStateException("Annotated type does not seem to be an Activity");
}
try {
generateMemento(elements, hostActivity, activityType);
} catch (IOException e) {
throw new RuntimeException("Failed writing class file", e);
}
return true;
}
private void handleAcceptParameters(RoundEnvironment roundEnvironment,
Element element,
ControllerModel controllerModel)
throws ProcessorException {
TypeElement typeElement = (TypeElement) element;
List<Element> annotatedElements = this.processorUtils.getMethodFromTypeElementAnnotatedWith(this.processingEnvironment,
typeElement,
AcceptParameter.class);
// validate
AcceptParameterAnnotationValidator.builder()
.roundEnvironment(roundEnvironment)
.processingEnvironment(processingEnvironment)
.controllerModel(controllerModel)
.listOfAnnotatedElements(annotatedElements)
.build()
.validate();
// add to ControllerModel ...
for (Element annotatedElement : annotatedElements) {
ExecutableElement executableElement = (ExecutableElement) annotatedElement;
AcceptParameter annotation = executableElement.getAnnotation(AcceptParameter.class);
controllerModel.getParameterAcceptors()
.add(new ParameterAcceptor(annotation.value(),
executableElement.getSimpleName()
.toString()));
}
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
if (roundEnv.processingOver())
return true;
TypeElement aliveRangeAnno = elements.getTypeElement("AliveRanges");
if (!annotations.contains(aliveRangeAnno)) {
error("no @AliveRanges annotation found in test class");
}
for (Element elem: roundEnv.getElementsAnnotatedWith(aliveRangeAnno)) {
Annotation annotation = elem.getAnnotation(AliveRanges.class);
aliveRangeMap.put(new ElementKey(elem), (AliveRanges)annotation);
}
return true;
}
private void processAnnotation(TypeElement annotationElement, RoundEnvironment roundEnv) {
roundEnv.getElementsAnnotatedWith(annotationElement)
.stream()
.filter(element -> element.getKind() == ElementKind.METHOD)
// Element is always ExecutableElement because it is a method.
.forEachOrdered(element -> {
try {
processMethod((ExecutableElement) element);
} catch (IOException e) {
final StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
processingEnv.getMessager().printMessage(
Kind.ERROR,
"Could not process all elements" + System.lineSeparator() + writer,
element);
}
});
}
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{
Elements elementUtils = processingEnv.getElementUtils();
TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_ATTRIBUTE_VALUE_TYPE_CLASS_NAME);
for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement))
{
boolean isAbstract = isAbstract(annotationElement, e);
if(!isAbstract)
{
checkAnnotationIsOnInterface(annotationElement, e);
}
if(!isContent(e))
{
checkAllMethodsAreAccessors(e, isAbstract);
}
}
return false;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Context context = ((JavacProcessingEnvironment) processingEnv).getContext();
FSInfo fsInfo = context.get(FSInfo.class);
round++;
if (round == 1) {
boolean expect = Boolean.valueOf(options.get("expect"));
checkEqual("cache result", fsInfo.isDirectory(testDir), expect);
initialFSInfo = fsInfo;
} else {
checkEqual("fsInfo", fsInfo, initialFSInfo);
}
return true;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
processImpl(roundEnv);
} catch (Exception e) {
// We don't allow exceptions of any kind to propagate to the compiler
try (StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter)) {
e.printStackTrace(printWriter);
fatalError(stringWriter.toString());
} catch (IOException ioe) {
fatalError("Could not close resources " + ioe);
}
}
// Universal processors should return false since other processor can be potentially acting on the same element
return false;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (first) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "proc warning");
try {
JavaFileObject file = processingEnv.getFiler().createSourceFile("Gen.java");
try (Writer writer = file.openWriter()) {
writer.write("class Gen {}");
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
first = false;
}
if (roundEnv.processingOver()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "proc error");
}
return false;
}
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
getSession().close();
return true;
}
for (TypeElement typeElement : annotations) {
for (Element mainClass : roundEnv.getElementsAnnotatedWith(typeElement)) {
JibBuild jib = mainClass.getAnnotation(JibBuild.class);
if (jib == null) {
continue;
}
process("jib", mainClass, JibBuild.class);
}
}
return false;
}
private void buildMixin(Element element, RoundEnvironment roundEnv, Context context) {
debugElement(element, "@Mixin");
if (element.asType().getKind() != TypeKind.DECLARED) {
error(element, "@Mixin must have a declared type, not %s", element.asType());
return;
}
TypeElement type = (TypeElement) ((DeclaredType) element.asType()).asElement();
CommandSpec mixin = buildCommand(type, context, roundEnv);
logger.fine("Built mixin: " + mixin + " from " + element);
if (EnumSet.of(ElementKind.FIELD, ElementKind.PARAMETER).contains(element.getKind())) {
VariableElement variableElement = (VariableElement) element;
MixinInfo mixinInfo = new MixinInfo(variableElement, mixin);
CommandSpec mixee = buildCommand(mixinInfo.enclosingElement(), context, roundEnv);
Set<MixinInfo> mixinInfos = context.mixinInfoMap.get(mixee);
if (mixinInfos == null) {
mixinInfos = new HashSet<MixinInfo>(2);
context.mixinInfoMap.put(mixee, mixinInfos);
}
mixinInfos.add(mixinInfo);
logger.fine("Mixin name=" + mixinInfo.mixinName() + ", target command=" + mixee.userObject());
}
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
List<BuckModuleDescriptor> buckModuleDescriptors =
collectBuckModuleDescriptors(annotations, roundEnv);
if (buckModuleDescriptors.isEmpty()) {
return false;
}
assertOneBuckModuleDescriptor(buckModuleDescriptors);
return generateBuckModuleAdapterPlugin(buckModuleDescriptors.get(0));
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!ran) {
ran = true;
ExecutableElement m = getFirstMethodIn("C");
System.err.println("method: " + m);
TypeMirror type = (DeclaredType)m.getParameters().get(0).asType();
System.err.println("parameters[0]: " + type);
if (!isParameterized(type))
throw new AssertionError(type);
type = ((ExecutableType)m.asType()).getParameterTypes().get(0);
System.err.println("parameterTypes[0]: " + type);
if (!isParameterized(type))
throw new AssertionError(type);
System.err.println();
}
return true;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
TestElementScanner s = new TestElementScanner();
for (Element e: roundEnv.getRootElements()) {
s.scan(e);
}
return true;
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (!roundEnvironment.processingOver()) {
processAnnotations(roundEnvironment);
}
return true;
}
private void buildOptions(RoundEnvironment roundEnv, Context context) {
logger.fine("Building options...");
Set<? extends Element> explicitOptions = roundEnv.getElementsAnnotatedWith(Option.class);
for (Element element : explicitOptions) {
buildOption(element, context);
}
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (set != null && !set.isEmpty()) {
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(InjectXModule.class);
if (elements == null || elements.size() <= 0) {
return true;
}
mLogger.info(String.format("解析注解:%s", InjectXModule.class.getSimpleName()));
try {
// key:依赖注入变量的目标类全限定名;value:目标类中携带@InjectXModule的Element的map集合
Map<String, List<Element>> targetInjectElements = new LinkedHashMap<>();
// 扫描注解InjectXModule
for (Element injectElement : elements) {
verify(injectElement);
String fullClzName = injectElement.getEnclosingElement().toString();
List<Element> injectElements = targetInjectElements.get(fullClzName);
if (injectElements == null) {
injectElements = new ArrayList<>();
targetInjectElements.put(fullClzName, injectElements);
}
injectElements.add(injectElement);
}
// 生成代码
generateCode(targetInjectElements);
} catch (ProcessException e) {
mLogger.error(e.fillInStackTrace());
}
return true;
}
return false;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
model = new PrefsModel();
parseBindType(roundEnv);
// Put all @BindSharedPreferences elements in beanElements
for (Element item : roundEnv.getElementsAnnotatedWith(BindSharedPreferences.class)) {
AssertKripton.assertTrueOrInvalidKindForAnnotationException(item.getKind() == ElementKind.CLASS, item, BindSharedPreferences.class);
analyzeSharedPreferences((TypeElement) item);
}
return true;
}
private void buildParameters(RoundEnvironment roundEnv, Context context) {
logger.fine("Building parameters...");
Set<? extends Element> explicitParameters = roundEnv.getElementsAnnotatedWith(Parameters.class);
for (Element element : explicitParameters) {
buildParameter(element, context);
}
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<? extends Element> builderTypes =
roundEnv.getElementsAnnotatedWith(RetroFacebook.Builder.class);
if (!SuperficialValidation.validateElements(builderTypes)) {
return false;
}
for (Element annotatedType : builderTypes) {
// Double-check that the annotation is there. Sometimes the compiler gets confused in case of
// erroneous source code. SuperficialValidation should protect us against this but it doesn't
// cost anything to check again.
if (isAnnotationPresent(annotatedType, RetroFacebook.Builder.class)) {
validate(
annotatedType,
"@RetroFacebook.Builder can only be applied to a class or interface inside an"
+ " @RetroFacebook class");
}
}
Set<? extends Element> validateMethods =
roundEnv.getElementsAnnotatedWith(RetroFacebook.Validate.class);
if (!SuperficialValidation.validateElements(validateMethods)) {
return false;
}
for (Element annotatedMethod : validateMethods) {
if (isAnnotationPresent(annotatedMethod, RetroFacebook.Validate.class)) {
validate(
annotatedMethod,
"@RetroFacebook.Validate can only be applied to a method inside an @RetroFacebook class");
}
}
return false;
}
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) {
if (!roundEnvironment.processingOver())
for(Element element : roundEnvironment.getRootElements())
element.accept(new LocalVarAllergy(), null);
return true;
}
void init(Set<? extends TypeElement> annotations, RoundEnvironment round, ProcessingEnvironment processing) {
this.components = MutableClassToInstanceMap.create();
this.processing = processing;
this.round = round;
this.annotations = ImmutableSet.copyOf(annotations);
this.initialized = true;
}
@Override
public final boolean process(
Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!testsRan) {
testsRan = true;
typeUtil = processingEnv.getTypeUtils();
runTests();
}
return false;
}