Adding / changing annotations in java project

We have a Java code library that we intend to use in projects. Some of these projects will require adding annotations to the Java objects in this library (i.e., in one project these objects will be used in the JAX-RS servlet implementation, so they need to be annotated using JAXB, JSON, etc. annotations). The problem I am facing is that I could not figure out how to add these annotations without changing the source library.

Consider the following example:

public class MyClass { private String field1; private int field2; } 

In some projects, I would like the class to behave as if it were

 public class MyClass { @Annotation1 private String field1; @Annotation2 private int field2; } 

Initially, I was thinking about using interfaces or derived classes that were separately annotated but couldn't figure out how to do this (whether it is possible or not). I also talked about the Javassist proposal in this thread (for example, the Java bytecode manipulation approach), but the problem is that this is necessary for working with Android clients, so this is not an option for me. At the moment I have no ideas.

I would appreciate if someone could help anyway. Maybe I missed something, or maybe what I'm trying to do is the wrong way. In any case, I need some guidance to continue.

Thank you very well in advance.

+6
source share
2 answers

I looked at this more and as a summary, here is what I found:

  • The Java language does not allow changing annotations at runtime.
  • You can use Javassist to change the java bytecode, but it does not work on platforms like Android.
  • You can use ASM , but this applies to working with the Java assembly (example here: http://community.jboss.org/thread/150002 ).

First of all, due to the fact that JAXB is not present on Android (and for other reasons), we switched to JSON and started using Jackson as an implementation. One of the benefits of this change was the ability to use what Jackson calls β€œmixed annotations,” which is exactly what I was looking for.

Here's a link that explains this more: http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html

+4
source

Failed to crack .class bytecode at runtime, this is not possible. You can use Javassist if you really want to dynamically change the bytecode of the library classes at runtime, but in the bigger picture this will probably end up exploding a lot.

I would suggest that you simply comment on the library and recompile its code base. If this is not the case, you can put the library classes / interfaces into your own classes / interfaces through inheritance and annotate there. In any case, I think it would be better to comment in code than during hacking bytecode at runtime. Added bonus, annotations in the source will be visible to the IDE, which will allow the IDE to better help you.

0
source

Source: https://habr.com/ru/post/896590/


All Articles