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
}
2
  • use adapter it suits better. Commented Feb 24, 2019 at 13:23
  • the real question is why do you need that? and this one can be answered in far better ways... Commented Feb 24, 2019 at 13:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

of course it's possible, you just need to alter the resulting byte code
@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.
Meanwhile in 2024 a lot of libraries are still missing @Nullable/@NotNull annotations that limit usefulness of automatic checkers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.