views:

63

answers:

3

It is possible to use Java class files which includes annotations that are not present at runtime?

Example: I want to write a class with the JPA @Embeddable annotation, which would be present at compile time (maven scope: "provided"). But the annoatation definition could be absent at runtime, if the class is used outside a JPA application.

A: 

You would have to either:

  1. Swap compiled classes at runtime (to include a class without the annotation.)
  2. Override the class definition of @Embeddable and remove @Retention(RUNTIME)
  3. Just prevent the class itself from being scanned by your JPA provider.
Lincoln
If I use the class outside a JPA application, 3. would always be met, right?
deamon
A: 

OSGi applications, for example Eclipse, will ignore annotations which aren't accessible, i.e. you won't get ClassNotFoundExceptions if you have a JPA annotation without the JPA api loaded.

Robert Wilson
A: 

For this particular problem I would simply define ORM mappings in XML resources instead of annotations. These mappings could be put in a different artifact (JAR) which would be added (or not) to the classpath depending on whether you use JPA or not.

lexicore