从JAR可执行文件中的外部类读取时缺少注释



我编写了一个程序从外部类读取注释并打印它们的名称:

public class Application {
public static void main(String[] args) {
for (Field field : Car.class.getDeclaredFields()) {
for (Annotation a : field.getAnnotations()) {
System.out.println(a.toString());
}
for (Annotation d : field.getDeclaredAnnotations()) {
System.out.println(d.toString());
}
}
}
}
public class Car {
@Id
private Integer carId;
@NotNull
private String carName;
}

调试时一切正常,但是当我编译并将其作为JAR可执行文件运行时,没有找到注释。作为JAR文件运行程序时,我如何获得注释?

因此,我将应用程序编译为JAR文件。要运行这个文件,我使用以下命令:

<output_path> $ java -jar <application-name>.jar

和我把我的Car类(编译为类)在:

<output_path>/code/com/example/base/myapp/classes/Car.class

查看RetentionPolicy中的注释。如果它是SOURCECLASS,你不应该期望在运行时看到它们。只有RUNTIME注释能够在运行时被反射地读取。

您还需要确保注释类在运行时位于类路径上。

下面是一个例子:

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
public class AnnotationExample {
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
@interface SourceAnnotation {
}
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
@interface ClassAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface RuntimeAnnotation {
}
@SourceAnnotation
@ClassAnnotation
@RuntimeAnnotation
int foo;

public static void main(String[] args) {
for (Field field : AnnotationExample.class.getDeclaredFields()) {
for (Annotation a : field.getAnnotations()) {
System.out.println(a.toString());
}
}
}
}

让我们编译它并查看类文件:

$ javac AnnotationExample.java
$ ls *.class
AnnotationExample$ClassAnnotation.class     AnnotationExample$SourceAnnotation.class
AnnotationExample$RuntimeAnnotation.class
AnnotationExample.class

如果我们运行:

$ java -cp . AnnotationExample
@AnnotationExample$RuntimeAnnotation()

现在我们删除注释的类文件:

$ rm AnnotationExample$RuntimeAnnotation.class
$ java -cp . AnnotationExample
$

没有错误,但是没有找到注释。

最新更新