Proxyを使った動的なBeanの実装

Beanを生成するクラスが次の通り。


import java.lang.reflect.Proxy;

public class DynaBean {

private Class clazz = null;

public DynaBean(Class clazz) {
this.clazz = clazz;
}

public Object newInstance() {
return Proxy.newProxyInstance(clazz.getClassLoader(),
new Class { clazz }, new DynaBeanInvocationHandler());
}

}

ハンドラが次の通り。インデックス付きのプロパティやネストされたプロパティは考慮していない。


package bodybuilder.builder.bean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

class DynaBeanInvocationHandler implements InvocationHandler {

private Map map = new HashMap();

public Object invoke(Object proxy, Method method, Object args)
throws Throwable {
String methodName = method.getName();
Object returnValue = null;

if (methodName.matches("^get.+$") && (args == null || args.length == 0)) {
returnValue = map.get(methodName.substring(3));
} else if (methodName.matches("^is.+$")
&& (args == null || args.length == 0)) {
returnValue = map.get(methodName.substring(2));
} else if (methodName.matches("^set.+$")
&& (args != null && args.length == 1)) {
map.put(methodName.substring(3), args[0]);
}

return returnValue;
}

}

で、テスト用のBeanインターフェース。


public interface SampleBean {

public String getName();

public void setName(String name);

public int getAge();

public void setAge(int age);

}

で、テストコード。


public class Hoge {

public static void main(String[] args) throws Exception {
DynaBean dbean = new DynaBean(SampleBean.class);
SampleBean bean = (SampleBean) dbean.newInstance();
bean.setName("山田");
bean.setAge(25);
System.out.println(bean.getName());
System.out.println(bean.getAge());
}

}

実行結果は次の通り。


山田
25