Skip to content

Instantly share code, notes, and snippets.

@cataphract
Created February 2, 2021 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cataphract/62a2a142656ecbca862bc32103b0081e to your computer and use it in GitHub Desktop.
Save cataphract/62a2a142656ecbca862bc32103b0081e to your computer and use it in GitHub Desktop.
import groovy.transform.CompileStatic
import java.lang.invoke.*
import static groovyjarjarasm.asm.Opcodes.H_INVOKESTATIC
class Logger {
private final String name
Logger(Class cls) {
name = cls.name
}
void log(String s) {
System.out.println "logger $name: $s"
}
}
@CompileStatic
class Helper {
static CallSite bootstrap(MethodHandles.Lookup lookup,
String callType,
MethodType type,
String className) {
println 'in bootstrap'
Logger logger = new Logger(Class.forName(className))
MethodHandle mh = MethodHandles.constant(Logger, logger)
new ConstantCallSite(mh)
}
}
class MyClass {
@groovyx.ast.bytecode.Bytecode
static void testLogging(String message) {
invokedynamic 'getLogger', '()LLogger;',
[H_INVOKESTATIC, 'Helper', 'bootstrap',
[CallSite, MethodHandles.Lookup, String, MethodType, String]],
'MyClass'
aload_0
invokevirtual 'Logger.log', '(Ljava/lang/String;)V'
return
}
}
2.times { MyClass.testLogging('da message') }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment