有2个类,没有任何关系,我现在一个类里面的属性都得到值了,我怎么样把这里面所有的值放到另外一个类对应的属性上.
  比如
 Sp sp =loginService.checkLogin_Sp(loginBean.getCspname());通过查询得到sp对象
 我现在有个KF类,我想把sp里面的东西放到KF类里面,因为我这里面除了放SP类里面的东西以外,我还要放其他类里面的东西.然后封装发出去.
 我也知道可以通过
  KF kf=new KF();
  kf.set(sp.get())的方法来设置,不过里面的属性太多了.有没有更方便的方法呢?

解决方案 »

  1.   

    一个一个的get 然后 set,如果属性名和方法名相同,可以用反射来做!
      

  2.   

    引用apache的commons-beanutils.jar包
    使用如下代码:
    BeanUtils.copyProperties(kf, sp)
      

  3.   

    如果符合javaBean 命名规范的话,我觉得可以使用反射,比如
                  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;
    }


    }