Are annotation class files needed in the runtime class path?

Go To StackoverFlow.com

9

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.

2012-04-05 17:10
by meriton
related links : http://mail.openjdk.java.net/pipermail/type-annotations-dev/2011-November/000079.html , https://bugs.eclipse.org/bugs/show_bug.cgi?id=366063 (for future quick reference - Jayan 2012-04-05 17:40
Possible dup: http://stackoverflow.com/questions/3567413/why-doesnt-a-missing-annotation-cause-a-classnotfoundexception-at-runtim - Matt McHenry 2012-04-05 18:27
Thanks Matt, that's exactly what I was looking for - meriton 2012-04-05 19:07


4

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.

I would expect even a AccessibleObject.getAnnotations() would cause exceptions. It is safe to the annotation types in the classpath.

2012-04-05 17:27
by Jayan
AccessibleObject.getAnnotations() doesn't cause exceptions with missing annotation at classpath - http://bugs.java.com/viewbug.do?bugid=632230 - kodstark 2017-11-10 10:31


0

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

2017-11-10 10:30
by kodstark
Ads