我有以下课程。两个注释( AnnotA 和 AnnotB ),一个类'孩子 .java'(带@AnnotA)及其'父'基 .java'(使用@AnnotB)。
编译Child.java时,我的注释处理器会返回 AnnotA ,但它不会报告Base.java中的注释( AnnotB )。
AnnotA.java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface AnnotA
{
}
AnnotB.java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface AnnotB
{
}
Base.java
@AnnotB
public class Base
{
}
Child.java
@AnnotA
public class Child extends Base
{
}
MyProc.java
import javax.annotation.processing.*;
import java.lang.annotation.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.tools.*;
import java.util.*;
import java.util.stream.*;
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class MyProc extends AbstractProcessor
{
@Override
public Set<String> getSupportedAnnotationTypes() {
final Set<String> set = new HashSet<>();
set.add("AnnotA");
set.add("AnnotB");
return set;
}
@Override
public boolean process(final Set<? extends TypeElement> annotations,
final RoundEnvironment roundEnv
) {
roundEnv.getElementsAnnotatedWith(AnnotA.class).stream().
forEach(E->{System.err.println("AnnotA>>" + E + " "+ E.getAnnotation(AnnotA.class));});
roundEnv.getElementsAnnotatedWith(AnnotB.class).stream().
forEach(E->{System.err.println("AnnotB>>" + E + " "+ E.getAnnotation(AnnotB.class));});
return true;
}
}
这是编译过程及其输出,如您所见,当Parent.java是Child.java的父项时,没有关于AnnotB的消息
rm -rf tmp
mkdir -p tmp/META-INF/services
javac -d tmp MyProc.java
echo "MyProc" > tmp/META-INF/services/javax.annotation.processing.Processor
jar cvf myproc.jar -C tmp .
added manifest
ignoring entry META-INF/
adding: META-INF/services/(in = 0) (out= 0)(stored 0%)
adding: META-INF/services/javax.annotation.processing.Processor(in = 7) (out= 9)(deflated -28%)
adding: AnnotB.class(in = 363) (out= 221)(deflated 39%)
adding: MyProc.class(in = 2512) (out= 1118)(deflated 55%)
adding: AnnotA.class(in = 363) (out= 221)(deflated 39%)
##
mkdir -p tmp
javac -processorpath myproc.jar -d tmp Child.java
AnnotA>>Child @AnnotA()
warning: Implicitly compiled files were not subject to annotation processing.
Use -implicit to specify a policy for implicit compilation.
1 warning
rm -rf tmp
这段代码有什么问题? 谢谢。