有2个类,没有任何关系,我现在一个类里面的属性都得到值了,我怎么样把这里面所有的值放到另外一个类对应的属性上.
比如
Sp sp =loginService.checkLogin_Sp(loginBean.getCspname());通过查询得到sp对象
我现在有个KF类,我想把sp里面的东西放到KF类里面,因为我这里面除了放SP类里面的东西以外,我还要放其他类里面的东西.然后封装发出去.
我也知道可以通过
KF kf=new KF();
kf.set(sp.get())的方法来设置,不过里面的属性太多了.有没有更方便的方法呢?
比如
Sp sp =loginService.checkLogin_Sp(loginBean.getCspname());通过查询得到sp对象
我现在有个KF类,我想把sp里面的东西放到KF类里面,因为我这里面除了放SP类里面的东西以外,我还要放其他类里面的东西.然后封装发出去.
我也知道可以通过
KF kf=new KF();
kf.set(sp.get())的方法来设置,不过里面的属性太多了.有没有更方便的方法呢?
使用如下代码:
BeanUtils.copyProperties(kf, sp)
public class ReflectionTest { /**
* @param args
*/
public static void main(String[] args) {
A a = new A();
a.setName("xxx");
a.setTitle("UUU");
Class clazzA = a.getClass();
Field[] fields = clazzA.getDeclaredFields();
B b = new B();
Method[] methodsOfA = a.getClass().getDeclaredMethods();
Method[] methodsOfB = b.getClass().getDeclaredMethods();
for(Method methodOfA : methodsOfA) {
if(methodOfA.getName().startsWith("get")) {
try{
Object value = methodOfA.invoke(a);
if(value != null) {
for(Method methodOfB : methodsOfB) {
String methodName = methodOfB.getName().toLowerCase();
String methodNameOfA = methodOfA.getName().toLowerCase();
String fieldName = methodNameOfA.substring(methodNameOfA.indexOf("get") + 3);
if(methodName.startsWith("set") && methodName.contains(fieldName)) { try{
methodOfB.invoke(b, value);
break;
} catch(Exception e) {
//ignore.
}
}
}
}
} catch(Exception e) {
//ignore.
}
}
}
System.out.println("name " + b.getName());
System.out.println("title " + b.getTitle());
}}class A {
public String name; private String title;
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
}
}class B {
public String name; private String title;
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
}
}