Is static metaprogramming possible in Java?

前端 未结 11 1173
無奈伤痛
無奈伤痛 2020-12-14 00:56

I am a fan of static metaprogramming in C++. I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in

11条回答
  •  悲哀的现实
    2020-12-14 01:13

    What do you exactly mean by "static metaprogramming"? Yes, C++ template metaprogramming is impossible in Java, but it offers other methods, much more powerful than those from C++:

    • reflection
    • aspect-oriented programming (@AspectJ)
    • bytecode manipulation (Javassist, ObjectWeb ASM, Java agents)
    • code generation (Annotation Processing Tool, template engines like Velocity)
    • Abstract Syntax Tree manipulations (APIs provided by popular IDEs)
    • possibility to run Java compiler and use compiled code even at runtime

    There's no best method: each of those methods has its strengths and weaknesses. Due to flexibility of JVM, all of those methods in Java can be used both at compilation time and runtime.

提交回复
热议问题