Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the JVM load the annotation class

I found that if I use an annotation, the program will not throw a ClassNotFoundException.

class A {
        @Transactional
        public void insert() {
            //insert something
        }
    }

Tomcat starts successefully without the javaee-api-7.0.jar which contains the class javax.transaction.Transactional

It makes me very confused, shouldn't the JVM throw a ClassNotFoundException when it loads the class A?

like image 644
hhhyyq Avatar asked Feb 18 '16 07:02

hhhyyq


1 Answers

No, it shouldn't. Annotations are just metadata. It's expected that byte-code containing annotations runs fine even if the annotation is not in the classpath. Of course, if some library tries to actually access and use the annotation that is not in the classpath, that won't work.

This is explicitely supported in order to be able, for example

  • to add annotations used by byte-code static analysis tools like FindBugs, that are in no use when running the code in production
  • to be able to use detached JPA entities in a client even though the server is the only one to actually use the JPA annotations
like image 82
JB Nizet Avatar answered Sep 28 '22 13:09

JB Nizet