0

I want to declare an annotation on class which is imported from a library.

For eg:

Original class present in some library from dependency

class A{
  int x;
  int y
}

Modified class

@someAnnotation
class A{
  int x;
  int y
}
Himanshu Goel
  • 574
  • 1
  • 8
  • 26

1 Answers1

1

Simple answer, you can't.

Longer answer. Depending on how you are using the library, you might be able to create a proxy class, that carries the annotation and inside it has the real class as a delegate, with all calls to the proxy delegated to the internal actual class. Assuming you can in some way use your proxy class instead. Overriding the class is another option, but it depends on whether the original class is final, and exposes what you want.

In reality, it is very likely that the reasons for you needing this are wrong. If you need to use some annotations, it is probably because you want to use some framework which recognises those annoatations. Making this library tightly coupled with this framework is probably a bad idea and bad design. Without more details of what annotations you are trying to add it is difficult to provide more useful information.

jbx
  • 21,365
  • 18
  • 90
  • 144
  • of course it's possible, you just need to alter the resulting byte code – Eugene Feb 24 '19 at 13:31
  • @Eugene hehe, fair enough. You need to alter the bytecode of the original library though, which would already be compiled in a jar file (presumably). Might as well get the source (if it is open source) and fork it to add the annotations. – jbx Feb 24 '19 at 14:01