简体   繁体   English

运行时 class 路径中是否需要注释 class 文件?

[英]Are annotation class files needed in the runtime class path?

If a class is annotated with an annotation, does the definition of that annotation have to be in the runtime classpath in order to use the class?如果 class 被注释了,那么该注释的定义是否必须在运行时类路径中才能使用 class? For example, given the annotation例如,给定注释

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {}

can I execute the program我可以执行程序吗

@Component
public class Test {
    public static void main(String[] args) {
        System.out.println("It worked!");
    }
}

without having Component.class in the classpath?类路径中没有 Component.class? (In my test I could, but is this behavior defined by the spec?) (在我的测试中我可以,但是这种行为是由规范定义的吗?)

I ask because there are conflicting claims whether using an annotation from a library creates a dependency on that library.我问是因为存在相互矛盾的说法,是否使用库中的注释会创建对该库的依赖。

Runtime annotations are meta information to be processed by annotation processor at the runtime.运行时注解是注解处理器在运行时处理的元信息。 If there is an access to annotation at runtime, you definitely add annotations in the classpath.如果在运行时访问注解,你肯定会在类路径中添加注解。 For example junit definitely need the annotations in the class path determine test methods.例如junit肯定需要class路径中的注解确定测试方法。

If there is no processing of annotation is done, there is no need to have it the classpath.如果没有完成注解处理,就没有必要让它成为类路径。

Yes you can execute program without having Component.class in the classpath.是的,您可以在类路径中没有 Component.class 的情况下执行程序。 More details here: Why doesn't a missing annotation cause a ClassNotFoundException at runtime?此处有更多详细信息: Why doesn't a missing annotation cause a ClassNotFoundException at runtime?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM