Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a method name to bean name at runtime?

I am working with BeanBinding a lot in my current project and so I have code that looks like...

TypeA objA;
TypeB objB;
Bindings.createAutoBinding(UpdateStrategy.READ, 
    objA,   BeanProperty.create("X"),
    objB,   BeanProperty.create("X"))
    .bind();

Where objA and objB are instances of classes that have a setX() method. The problem comes in that if I refactor setX to setY then I need to hunt down these string property names. I realize I can create static final strings for property name but if I can get the compiler to do the work for me, all the better.

Ideally, what I would like to be able to do is...

TypeA obja;
TypeB objB;
Bindings.createAutoBinding(UpdateStrategy.READ, 
    objA,   BeanProperty.create( Magic.returnBeanName(TypeA.class).getX() ),
    objB,   BeanProperty.create( Magic.returnBeanName(TypeB.class).setX() )
    .bind();

It would seem this could be possible via some code synthesis and/or aspects.

like image 284
Andrew White Avatar asked Aug 08 '11 17:08

Andrew White


1 Answers

A complete shot in the dark, but maybe returnBeanName can use javassist to create a different class similar to the bean, except that it modifies the return types of the getters to String and returns the property name?

For example, if your bean looks like this:

public class Foo{
    private int x;

    public int getX(){
        return x;
    }

    public void setX(int x){
        this.x= x;
    }
}

Then dynamically create a different class that looks like this:

public class FooMeta{
    public String getX(){
        return "x";
    }
}

Seem kind of crazy, but sounds fun to write.

like image 172
Jeremy Avatar answered Sep 30 '22 21:09

Jeremy