不能使用BeanUtils将一个类的特性复制到另一个类

时间:2016-07-31 16:07:35

标签: java class copy apache-commons-beanutils

我有一段代码,我使用BeanUtils.copyProperities(dest, orig)将一个类的相似特性复制到另一个类。然而。这不起作用。我收到错误:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

我正在使用BeanUtils 1.9.2,Java 8,Windows 10,Eclipse。

import org.apache.commons.beanutils.*;

public class Main{
    public Main(){
        Entity entity = new Entity();
        AbstractGameObject aEntity = new AbstractGameObject();
        try {
            BeanUtils.copyProperties(aEntity, entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(aEntity.similar); // Should print out 10, No?;
    }
    public static void main(String[] args) {
        Main main = new Main();
    }
    private class Entity{
        int similar = 10;
        int differentE = 9;
        public Entity(){

        }
    }
    private class AbstractGameObject{
        int similar = 2;
        int differentA = 1;
        public AbstractGameObject(){

        }
    }
}

2 个答案:

答案 0 :(得分:1)

重要:类必须是public,copyProperties使用setter和getter。 试试:

public class Main {
    public Main()  {
        Entity entity = new Entity();
        AbstractGameObject aEntity = new AbstractGameObject();

        try {
            BeanUtils.copyProperties(aEntity, entity);
        } catch (Exception ex) {
            // use a logger
        }
        System.out.println(aEntity.similar);
        System.out.println(entity.similar);
    }

    public static void main(String[] args){
        Main main = new Main();
    }

    public class Entity {

        private int similar = 10;
        private int differentE = 9;

        public int getSimilar() {
            return similar;
        }

        public void setSimilar(int similar) {
            this.similar = similar;
        }

        public int getDifferentE() {
            return differentE;
        }

        public void setDifferentE(int differentE) {
            this.differentE = differentE;
        }        

    }

    public  class AbstractGameObject {

        private int similar = 2;
        private int differentA = 1;

        public int getSimilar() {
            return similar;
        }

        public void setSimilar(int similar) {
            this.similar = similar;
        }

        public int getDifferentA() {
            return differentA;
        }

        public void setDifferentA(int differentA) {
            this.differentA = differentA;
        }

    }
}

答案 1 :(得分:0)

此外,请注意,如果您使用Lombok来生成公共获取程序和设置程序,BeanUtils.copyProperties()将不起作用。您必须手动创建它们。