The document discusses various metaprogramming techniques in Java, including annotations, reflection, bytecode manipulation libraries like ASM and BCEL, Java agents, and dynamic languages like Groovy. It provides examples of using annotations to mark classes as commands, reflecting on annotated classes, enhancing classes at runtime by modifying bytecode with ASM, and dynamically adding methods in Groovy using its metaprogramming features.
32. ● Introduce Interface (or Superclass)
● Change visibility
● Add new method
● Add new field
● Replace method body
● Merge two classes into one
Class Transformations
38. @Command("hi")
public class Hi {
public void exec() {
System.out.println(this.getClass().getName());
System.out.println("Hello annotations!");
}
}
Hi
43. def list = ['Java', 'Groovy', 'Scala']
LanguageList() {
def mc = new ExpandoMetaClass(LanguageList, false, true)
mc.initialize()
this.metaClass = mc
}
def methodMissing(String name, args) {
// Intercept method that starts with find.
if (name.startsWith("find")) {
def result = list.find { it == name[4..-1] }
// Add new method to class with metaClass.
this.metaClass."$name" = {-> result + "[cache]" }
result
} else {
throw new MissingMethodException(
name, this.class, args)
}
}
Groovy missing method