3 ms·
If you are using reflection and encountering performance problems, the correct approach is pretty much always to write an annotation processor and generate that
by hota_mazi 9y ago
If you are using reflection and encountering performance problems, the correct approach is pretty much always to write an annotation processor and generate that code instead.
- avodonosov 9y agoOr generate code without using annotation processor
- specialist 9y agoReflectASM is the fastest, most general purpose reflection solution. It uses runtime bytecode generation. https://github.com/EsotericSoftware/reflectasm https://github.com/EsotericSoftware/reflectasm When I needed something more custom, I've done the bytecode strategy a few times, using ASM library or equiv. But the cost of change (brittleness, aggravation) is pretty high. Now I just write Java source and use the JDK's built-in javac to generate the bytecodes. Some people like StringTemplate. http://www.stringtemplate.org http://www.stringtemplate.org For whatever reason, I still prefer Velocity. Template languages are mostly evil, and variations of terrible, so I just stick to what I know. Annotations are never the correct answer. For any use case, purpose. Edit: Whoops. May have spoke too soon. JDK 8's MethodHandle and some other features (inlining simple getters) may have mooted ReflectASM. https://github.com/EsotericSoftware/reflectasm/issues/23 https://github.com/EsotericSoftware/reflectasm/issues/23 I may have to retool some of my older code.
- hota_mazi 9y ago> Annotations are never the correct answer. For any use case, purpose That's a pretty absurd claim, especially given their popularity. What do you use to annotate elements present in a Java source with metadata?
- tpxl 9y agoWhy XML of course!
- wtetzner 9y agoJavaPoet is a relatively nice library for generating Java sources: https://github.com/square/javapoet https://github.com/square/javapoet
- specialist 9y agoThanks. I tried JavaPoet, once apon a time. I'm just a simple bear. I can't keep all the details straight. One strategy I use to cope is round tripping, as a way to confirm I get the expected results. My current approach to code generation: painstakingly hand craft the desired source code output. Then turn that into a template (progressive refinement). Then compare (diff) generated output to manual. Iterate. Many times that means adjusting target to make it easier to generate. Using bytecodes (class file) as the target output adds complexity and more steps. I've been reversing bytecodes for a long time, manually using javap, the decompilers (which are now quite good), and using ASMs code generator plugin for Eclipse (super clever). But it's too fussy, compared to the Java source code strategy.