gpt4 book ai didi

Java注释处理器忽略父类中的注释

转载 作者:行者123 更新时间:2023-11-30 02:31:10 25 4
gpt4 key购买 nike

我有以下类(class)。两个注释(AnnotAAnnotB),一个类“Child.java”(带有 @AnnotA)及其“父级”Base .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
{
}

基础.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;
}
}

这是编译过程及其输出,如您所见,没有关于 AnnotB 的消息,而 Parent.java 是 Child.java 的父级

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

这段代码有什么问题?谢谢。

最佳答案

关于Java注释处理器忽略父类中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44244579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com