import java.lang.reflect.InvocationTargetException;
public class BeanUtils {
public static Object getProperty (Object bean, String name) {
Class c = bean.getClass();
try {
Method m = c.getDeclaredMethod(name, new Class[0]);
return m.invoke(bean, new Object[0]);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public static void copyProperty (Object org, Object dest) {
Class orgClass = org.getClass();
Class destClass = dest.getClass();
Method[] orgMethods = orgClass.getMethods();
Method[] destMethods = destClass.getMethods();
for (Method md : destMethods) {
if (md.getName().indexOf("set") != -1) {
for (Method mo : orgMethods) {
if (mo.getName().indexOf("get") != -1 &&
mo.getName().substring(mo.getName().indexOf("get") + 3).equals(md.getName().substring(md.getName().indexOf("set") + 3))) {
try {
md.invoke(dest, mo.invoke(org, null));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
public boolean isEmpty() throws IllegalArgumentException, IllegalAccessException{
boolean flg = true;
Class c = this.getClass();
for (Field f : c.getDeclaredFields()) {
f.setAccessible(true);
if (f.getType().getSimpleName().equals("String")) {
if (f.get(this) != null) {
flg = false;
}
} else if (f.getType().getSimpleName().equals("int")) {
if (0 != (Integer)f.get(this)) {
flg = false;
}
}
}
return flg;
}
上面的代码只是今天做的几个小练习,为了备忘放在这上面。
今天下了个Apache的BeanUtils包,有时间详细研究下真正BeanUtils中的方法