java bean賦值工具類
實現接收的bean賦值,判斷有沒有對應值的get、set方法,有就賦值。
public static <T> void print(T bean) {
Class<?> fromClass = bean.getClass();
Method[] toClassMethods = fromClass.getMethods();
//遍歷to含有的方法
for (Method method : toClassMethods) {
String methodName = method.getName();
// 如果該方法是set方法
if (methodName.startsWith("setName")) {
try {
// 執行set方法設置to的值
method.invoke(bean, "sasd");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
System.out.println(bean.toString());
}