metaprogramming AND jvm – with CGLib and Plastic – 'bout



metaprogramming AND jvm – with CGLib and Plastic – 'bout

0 0


metaprogramming-in-java-slides


On Github wojtekerbetowski / metaprogramming-in-java-slides

metaprogramming AND jvm

with CGLib and Plastic

Maciej Jankowski

Wojtek Erbetowski

'bout

Wojtek Erbetowski
WJUG, Warsjawa 2012
http://[blog.]erbetowski.pl
@wojtassj

working in Polidea

Groovy, Java, Scala, Python, JS developer

RoboSpock

Code + docs at Polidea/RoboSpock

a class?

Instances of the class Class represent classes and interfaces in a running Java application.

Where to find it

new class() ?

public static Class<?> forName(String name, boolean initialize,
        ClassLoader loader) throws ClassNotFoundException{
    if (loader == null) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            ClassLoader ccl = ClassLoader.getCallerClassLoader();
            if (ccl != null) {
                sm.checkPermission(
                    SecurityConstants.GET_CLASSLOADER_PERMISSION);
            }
        }
    }
    return forName0(name, initialize, loader);
}

Class for name

private static native Class forName0(...)

classloaders

A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class.

Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class.

A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

oh yeah!

protected final Class<?> defineClass(
        String name, byte[] b, int off, int len)

hello world

Use some libs

The very low level libraries
ObjectWeb ASM
Javassist

Javassist

  • PowerMock
  • Play!Framework
  • Robolectric
  • Spring 3.2?

ASM

  • CGLib
  • Terracota
  • Cobertura
  • Groovy
  • Clojure
  • Byteman

CGLib

  • Hibernate
  • Spring
  • Guice
  • jMock
  • Mockito
  • Tumbler

typical mission

Cache
Mock/Stub/Spy
Transaction
Contracts
Logging
Performance (optimization, profiling)
ORM
Security

taking api higher

ASM Hello World!
ClassWriter cw = new ClassWriter(0);
FieldVisitor fv;
MethodVisitor mv;
AnnotationVisitor av0;

cw.visit(49,
    ACC_PUBLIC + ACC_SUPER,
    "Hello",
    null,
    "java/lang/Object",
    null);

cw.visitSource("Hello.java", null);

{
    mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL,
        "java/lang/Object",
        "<init>",
        "()V");

    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
}
{
    mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC,
        "main",
        "([Ljava/lang/String;)V",
        null,
        null);
    mv.visitFieldInsn(GETSTATIC,
        "java/lang/System",
        "out",
        "Ljava/io/PrintStream;");
    mv.visitLdcInsn("hello");
    mv.visitMethodInsn(INVOKEVIRTUAL,
        "java/io/PrintStream",
        "println",
        "(Ljava/lang/String;)V");
    mv.visitInsn(RETURN);
    mv.visitMaxs(2, 1);
    mv.visitEnd();
}
cw.visitEnd();

return cw.toByteArray();

Taking api higher

public class WeekendBlocker implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation)
            throws Throwable {

        Calendar today = new GregorianCalendar();
        if (today.getDisplayName(DAY_OF_WEEK, LONG, ENGLISH)
                .startsWith("S")) {

            throw new IllegalStateException(
                invocation.getMethod().getName()
                    + " not allowed on weekends!");
        }

        return invocation.proceed();
    }
}

public class NotOnWeekendsModule extends AbstractModule {
    protected void configure() {
        bindInterceptor(
            Matchers.any(),
            Matchers.annotatedWith(NotOnWeekends.class),
            new WeekendBlocker());
    }
}

let's define stuff

Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime.

Aspects

AOP (Aspect Oriented Programming)

AOP alliance

see api