meriton
meriton

Reputation: 70564

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? 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? (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.

Upvotes: 13

Views: 3852

Answers (2)

kodstark
kodstark

Reputation: 490

Yes you can execute program without having Component.class in the classpath. More details here: Why doesn't a missing annotation cause a ClassNotFoundException at runtime?

Upvotes: 1

Jayan
Jayan

Reputation: 18459

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.

If there is no processing of annotation is done, there is no need to have it the classpath.

Upvotes: 6

Related Questions