We have a library of Java code that we intend to use across projects. Some of these projects will require having annotations added to the Java objects in this library (i.e. in one project, these objects will be used in a JAX-RS servlet implementation so they need to be annotated with JAXB, JSON etc annotations). The issue I am having is that I could not figure out how to add these annotations without changing the original library.
Consider this example:
public class MyClass
{
private String field1;
private int field2;
}
In some projects, I would like the class to behave as if it was
public class MyClass
{
@Annotation1
private String field1;
@Annotation2
private int field2;
}
Initially I thought about using interfaces or derived classes that are separately annotated but could not figure out how to do it (or whether it is possible or not). I also found about the Javassist suggestion in this thread (i.e. Java bytecode manipulation approach) but the issue is that this needs to work on Android clients as well so it is not an option for me. At this point I am out of ideas.
I would appreciate if someone could help in any way. Maybe I am missing something, or maybe what I am trying to do is not the right way. In any case, I need some guidance now in order to proceed.
Thanks very much in advance.
Introduction. Java annotations are a mechanism for adding metadata information to our source code. They're a powerful part of Java that was added in JDK5. Annotations offer an alternative to the use of XML descriptors and marker interfaces.
Custom annotation is a user-defined annotation to provide metadata. We can use it when we want to store the custom meta for class, methods, constructor or field.
I looked into this more and as a summary, here's what I found:
Primarily due to JAXB not being present on Android (and other reasons) we switched to JSON and starting using Jackson as the implementation. One benefit of this change was the ability to use what Jackson calls "mixed-in annotations" which is exactly what I was looking for.
Here's the link that explains it more: http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With