public class BeanToForm<T extends Object, F extends ActionForm> implements Cloneable{
/**
* the method base on the fact that the bean's all methods is strictly observe java beans agreement
* @param f the source bean
* @param t the objective bean
* @return if they are successfully transformed,return true;else false
*/
private static boolean transform(Object f, Object t) {
try {
// put f to hashtable
Method[] temp = Class.forName(f.getClass().getName()).getMethods();
Hashtable<String, Method> from = new Hashtable<String, Method>();
for (int len = 0; len < temp.length; len++) {
if (temp[len].getName().startsWith("get")
&& temp[len].getParameterTypes().length == 0) {
from.put(temp[len].getName().substring(1), temp[len]);
}
}
// put t to hashtable
temp = Class.forName(t.getClass().getName()).getMethods();
Hashtable<String, Method> to = new Hashtable<String, Method>();
for (int len = 0; len < temp.length; len++) {
if (temp[len].getName().startsWith("set")
&& temp[len].getParameterTypes().length == 1) {
to.put(temp[len].getName().substring(1), temp[len]);
}
}
Iterator<String> it = from.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
if (to.containsKey(key)
&& to.get(key).getParameterTypes()[0].equals(from.get(
key).getReturnType())) {
to.get(key).invoke(t, from.get(key).invoke(f));
}
}
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* the method base on the fact that the bean's all methods is strictly observe sun javabean agreement
* @param <AF> extends org.apache.struts.action.ActionForm
* @param <O> extends java.lang.Object
* @param bean bean to transform
* @param form transformed bean
* @return if they are successfully transformed,return true;else false
*/
public static <AF extends ActionForm, O extends Object> boolean Bean2Form(
O bean, AF form) {
return transform(bean, form);
}
/**
* the method base on the fact that the bean's all methods is strictly observe sun javabean agreement
* @param <AF> extends org.apache.struts.action.ActionForm
* @param <O> extends java.lang.Object
* @param form transformed bean
* @param bean bean to transform
* @return if they are successfully transformed,return true;else false
*/
public static <AF extends ActionForm, O extends Object> boolean Form2Bean(
AF form, O bean) {
return transform(form, bean);
}
}
[Quote=引用 1 楼 Landor2004 的回复:]
合并不了,最简单的就是在actionForm中声明一个实体bean的变量,顺便要进行初始化
public class XxxForm{
private User user;
{
user = new User();
}
......
}
[/Quote]
public class UserForm extends ActionForm {
private User user = new User();
//setter
//getter
}
[Quote=引用 1 楼 Landor2004 的回复:]
合并不了,最简单的就是在actionForm中声明一个实体bean的变量,顺便要进行初始化
public class XxxForm{
private User user;
{
user = new User();
}
......
}
[/Quote]