1

只是为了理解 Dozer,我创建了两个类 PrimaryType 和 SecondaryType 并尝试使用 Dozer 映射它们。推土机能够无缝地映射它们。

尝试将 SecondaryType 的构造函数设为私有,但 Dozer 仍然成功地创建了 SecondaryType 类型的对象并能够映射其字段。谁能解释推土机如何实例化一个具有私有构造函数的类?

PrimaryType.java

package in.yogi;

public class PrimaryType
{
    private String name;
    private int age;

    public PrimaryType(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "PrimaryType [name=" + name + ", age=" + age + "]";
    }

}

SecondaryType.java

package in.yogi;

public class SecondaryType
{
    private String name;
    private int age;
    private SecondaryType() {

    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "SecondaryType [name=" + name + ", age=" + age + "]";
    }
}

AppMain.java

package in.yogi;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

import in.yogi.PrimaryType;

public class AppMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("This is the main Application!!!");
        PrimaryType sourceObject = new PrimaryType("Munsamy", 20);
        System.out.println(sourceObject);
        Mapper mapper = new DozerBeanMapper();
        SecondaryType destObject =  
            mapper.map(sourceObject, SecondaryType.class);
        System.out.println(destObject);
    }
}

输出:

PrimaryType [name=Munsamy, age=20]
log4j:WARN No appenders could be found for logger (org.dozer.config.GlobalSettings).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
SecondaryType [name=Munsamy, age=20]
4

1 回答 1

2

这通常通过反射来完成。推土机文档解释说:

bean 映射器是用 Java 编写的,并且严重依赖 Jakarta Commons Bean Utils 包来获取 Java Bean 实用程序方法。

阅读Commons Beanutils项目的文档,您可以找到所需的解释:

Java 语言提供反射自省API(请参阅 JDK Javadocs 中的java.lang.reflectjava.beans包)。但是,这些 API 可能很难理解和使用。BeanUtils 组件围绕这些功能提供了易于使用的包装器。

您可以自己轻松完成:

public static void main(String[] args) throws Exception {
    Constructor<SecondaryType> constructor = SecondaryType.class.getDeclaredConstructor();
    constructor.setAccessible(true); // if not set accessible, you will get an exception
    SecondaryType instance = constructor.newInstance();
    System.out.println(instance);
}
于 2016-02-01T07:13:50.757 回答