Arquivo mensal: novembro 2008

Mirror DSL 1.2 – reflection made easier

Mirrors

Last sunday was released the Mirror DSL 1.2.

Mirror is a simple DSL layer over the Java Reflection API, with the intent of helping writing reflection code in a cleaner and non-intrusive manner.

Nowadays, if you have to write code that takes advantage of the Java Reflection API for setting a property value, for instance, you should write a cumbersome code like that:

Field toSet = null;
for (Field f : target.getClass().getDeclaredFields()) {
    if (f.getName().equals("field")) {
        toSet = f;
    }
}
if (toSet != null && ((toSet.getModifiers() & Modifier.STATIC) == 0)
        && ((toSet.getModifiers() & Modifier.FINAL) == 0)) {
    toSet.setAccessible(true);
    toSet.set(target, value);
}

While, with mirror you could do everything that this awful code does, in a single line, and also in a very expressive way. You could just say to mirror: “Hey, Mirror, please on the object referred by “target” set the field called “fieldName” with the value of this variable here”.

But, how to do that with Java code? Simple:

Mirror.on(target).set().field("fieldName").withValue(value);

You can find more information about Mirror at: http://projetos.vidageek.net/mirror/

We hope that everybody find it useful, and it would be of an enourmous pleasure to get your feedback about it.

Etiquetado ,
Seguir

Obtenha todo post novo entregue na sua caixa de entrada.