Search in sources :

Example 1 with SmartClassWriter

use of com.facebook.presto.bytecode.SmartClassWriter in project presto by prestodb.

the class BytecodeExpressionAssertions method execute.

public static Object execute(Function<Scope, BytecodeNode> nodeGenerator, ParameterizedType returnType, Optional<ClassLoader> parentClassLoader) throws Exception {
    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName("Test"), type(Object.class));
    MethodDefinition method = classDefinition.declareMethod(a(PUBLIC, STATIC), "test", returnType);
    BytecodeNode node = nodeGenerator.apply(method.getScope());
    method.getBody().append(node);
    if (DUMP_BYTE_CODE_TREE) {
        DumpBytecodeVisitor dumpBytecode = new DumpBytecodeVisitor(System.out);
        dumpBytecode.visitClass(classDefinition);
    }
    DynamicClassLoader classLoader = new DynamicClassLoader(parentClassLoader.orElse(BytecodeExpressionAssertions.class.getClassLoader()));
    ClassWriter cw = new SmartClassWriter(ClassInfoLoader.createClassInfoLoader(ImmutableList.of(classDefinition), classLoader));
    classDefinition.visit(cw);
    Class<?> clazz = classLoader.defineClass(classDefinition.getType().getJavaClassName(), cw.toByteArray());
    return clazz.getMethod("test").invoke(null);
}
Also used : DynamicClassLoader(com.facebook.presto.bytecode.DynamicClassLoader) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) DumpBytecodeVisitor(com.facebook.presto.bytecode.DumpBytecodeVisitor) BytecodeNode(com.facebook.presto.bytecode.BytecodeNode) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition) SmartClassWriter(com.facebook.presto.bytecode.SmartClassWriter) ClassWriter(org.objectweb.asm.ClassWriter) SmartClassWriter(com.facebook.presto.bytecode.SmartClassWriter)

Aggregations

BytecodeNode (com.facebook.presto.bytecode.BytecodeNode)1 ClassDefinition (com.facebook.presto.bytecode.ClassDefinition)1 DumpBytecodeVisitor (com.facebook.presto.bytecode.DumpBytecodeVisitor)1 DynamicClassLoader (com.facebook.presto.bytecode.DynamicClassLoader)1 MethodDefinition (com.facebook.presto.bytecode.MethodDefinition)1 SmartClassWriter (com.facebook.presto.bytecode.SmartClassWriter)1 ClassWriter (org.objectweb.asm.ClassWriter)1