Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 813
meriton Avatar asked Apr 05 '12 17:04

meriton


2 Answers

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.

like image 67
Jayan Avatar answered Oct 19 '22 18:10

Jayan


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?

like image 1
kodstark Avatar answered Oct 19 '22 18:10

kodstark