I have situation where I cannot add annotations to class, but is there any way to add some kind of meta data to bean (code) that you cannot edit, but what would survive refactoring? What if I extend bean and then add annotations to that class is that possible?
The old way, use marker interfaces, that is interfaces without methods like Serializable or Cloneable.
Depending on your IDE, all you need to do is refer to your class or methods or fields in a text files such a properties or XML. Your IDE will find these and offer to perform a text find/replace when you rename classes/method/fields. (Though some refactors such a moving a method to another class won't work so well)
You could consider AOP
http://static.springsource.org/spring/docs/2.5.x/reference/aop.html
It allows you to externally add behaviour to specific methods, without editing your class. The extra code can be before, after, or around methods.
Without telling us exactly what you want to achieve, it's hard to guess what you need.
Do you need meta data for use from some other code or it should be readable for human?
You can use code instrumentation to add any data into your classes (javassist, some aop etc)
You could add a parallel class hierarchy with meta data. Sort of like the BeanInfo classes provide meta data for Java beans.
If you can't modify the code, you could put the meta data in a global map, with the Class as the key.
Related
Is it possible that use self defined Annotation to classify java class into different product function ? (Following are my thoughts)
If not, are there any other method to achieve the same purpose in Android project?
Step1: use self defined annotation to make clear java class's function
#SelfDefinedAnnotation( "product-function-a" )
class MyClass {
void func() {
//do something
}
}
Step2: during building period, generate a mapping file like this
MyClass -> product-function-a
YourClass -> product-function-b
I'm not sure about android (never worked with it), but in pure java its possible for sure.
You should define an annotation with retention policy SOURCE and since you're talking about build time, define an annotation processor. This is something that is "hooked" into the compilation process and allows creating such a mapping (I assume you want to store it in some kind of file, maybe *.properties file, or even generate a java source code with these definitions.
The annotation processor is broad topic, there are many ways to register them, so it pretty much depends on how do you build your stuff exactly, but its a general direction.
Please check out this tutorial it talks about annotation processors, the ways to register them, to associate with your custom annotation and so forth.
One suggestion though, if you're about to generate Java Source class and not just a properties file, this tutorial goes "low level" and tries to prepare the syntax by itself, I suggest using a much nicer (IMO) Java Poet library that will help to generate a proper java code
Say I have a class with a few fields all marked with a custom annotation. In my case it is #inject, because this is being used for dependency injection. How can I run a method in a separate class each time that annotation is used in my a class? In other words, each time a class is loaded the annotation runs a method that will collect the field data and in turn set the field.
I already have the entire system set up for collecting the resources, but I need some direction on how to actually run that code when the class with #inject annotation is loaded. Is this something that can be done by defining some sort of method in the annotation interface that performs the data collection?
My initial thought is to use a custom class loader, but I don't want to have to set the class loader when I use this jar in other projects. Is there a way to set a custom class loader programmatically for specific classes at runtime? I'm already doing a lot of pre-runtime reflection stuff and i'll already know which classes need to be loaded with a custom loader. Its just a matter of not knowing or if its even possible to set a custom loader on a class from within the code.
Can a classloader even be used to perform tasks such as pre-populating fields, or am I running off on a wrong tangent here? I just need a little direction on the most common way this type of thing is done (pre-populating class fields at runtime).
I was overthinking this problem. You cannot actually run code automatically prior to loading a class (unless its a servlet filter etc). In my situation the answer was to create an instance based on a specific class that already held the resource data I needed. Similar to how Google's Guice does it.
See this question for more insight: How does Guice Populate Annotated Fields
You can use injectors from Google Guice or Spring Framework.
I would like to build my own custom DI framework based on Java annotations and I need a little direction to get started. I know it would be much easier to use one of the many wonderful frameworks out there such as guice or spring, but for the sake of my own curiosity, i'd like to build my own.
I'm not very familiar with annotations, so i'm having a bit of trouble finding resources and would really appreciate someone just sort of spelling out a few of the steps i'll need to take to get started.
As fore mentioned, id like to take a factory approach and somehow label my getters with an #Resource or #Injectable type annotation, and then in my business classes be able to set my variable dependencies with an #Inject annotation and have the resource automatically available.
Does anyone have any sort of resource they can pass along to help me understand the process of tagging methods based on annotations and then retrieving values from a separate class based on an annotation. A little direction is all I need, something to get me started. And of course i'll be happy to post a little code sample here once I get going, for the sake of others future reading of course.
EDIT
The resources I am using to put this together:
Java Reflection: Annotations
How to find annotations in a given package: Stack Overflow ?
Scanning Annotations at Runtime
I have not actually finished writing this yet, but the basic task list is going to be as follows (for anyone who might be interested in doing something similar in the future)
At class runtime scan for all #Inject fields and get object type.
Scan all classes (or just a specific package of classes (I haven't
decided yet)) for annotated methods #InjectableResource.
Loop all annotated methods and find the method that returns the
object type I am looking for.
Run the method and get the dependency.
It will also be helpful to note that when scanning all the classes I will be using a library called Javassist. Basically what this does is allows me to read the bytecode information of each class without actually loading the class. So I can read the annotation strings without creating serious memory problems.
Interesting that you want to build your own. I love Google Guice - it makes code so elegant and simple.
I've used this guide before which I found pretty useful for learning about annotations and how you can pull them out of classes and methods.
You will have to define your own Annotations which is done using #interface. Then you will have to define some kind of class for doing bindings e.g. where you see an interface bind in this concrete class. Finally, you will need some logic to pull it altogether e.g. go through each class, find each annotation, and then find a suitable binding.
Give consideration to things like lazy instantiation through Reflections and singletons. Guice, for example, allows you to use a singleton so your only using one instance of the concrete class, or you can bind a new version each time.
Good luck!
Have a look at the following methods:
java/lang/Class.html#getAnnotation(java.lang.Class)
java/lang/Class.html#getAnnotations()
java/lang/Class.html#getDeclaredAnnotations()
Methods of the same name also exist for the java/lang/reflect/Method, java/lang/reflect/Field and java/lang/reflect/Constructor classes.
So in order to use these sorts of methods, you need to know a bit about Java reflection.
I've seen it used, but I'm not sure the usage were good usecase examples. Do you have examples of idiomatic usages of Guice Mapbinder? (Cases where Mapbinder is really the correct tool to solve a problem)
Offhand, it looks like a reasonable way to create a registry of runtime-named implementations of a common interface. Consider selecting one of many plugins/modes/whatever from a command line or configuration file: the desired injection can't be known at compile time. A MapBinder provides an easy runtime lookup without resorting to type-switching.
I extensively use it in Guts-GUI.
You can take a look, in particular, at the ResourceModule, where it is used to map the right ResourceConverter<T> for a given type T:
Map<TypeLiteral<?>>, ResourceConverter<?>>
The MapBinder is directly created in the Resources helper class.
This way, any module can add its own resource converters for its own types, e.g. MessageModule adds its own converters.
I also used it as Map<Integer, WindowProcessor>> in WindowsModule to define an ordered list of WindowProcessors to be applied, one after another, to a newly created window..
Once again, this allows various modules to insert their own processor to the list applied to every window: ResourceModule uses it to add the ability of automatic injection of i18n resources to windows.
Is it possible to add "hooks" to a class via bytecode enhancement that execute code whenever a class field is read or written? For example, I'd like to automatically set a "dirty" flag whenever a new value is assigned to a field.
If so, which libraries are best suited to implement this functionality?
I'd suggest you to read about AspectJ. Probably this is the tool you are looking for.
Here is how to generate getters and setters using the ASM framework. That should get you started.
http://asm.ow2.org/doc/faq.html#Q9
You can even let your bytecode-rewriter hook into the class-loader and do the rewriting on the fly.