为了理解Dozer,我创建了两个类PrimaryType和SecondaryType,并尝试使用Dozer来映射它们。 Dozer 能够无缝地绘制它们。
尝试将SecondaryType的构造函数设置为私有(private),但Dozer仍然成功地创建了SecondaryType类型的对象并能够映射其字段。谁能解释一下 Dozer 如何实例化一个具有私有(private)构造函数的类?
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]
最佳答案
这通常是通过 reflection 完成的。 Dozer documentation解释:
The bean mapper is written in Java and relies heavily on the Jakarta Commons Bean Utils package for Java Bean utility methods.
阅读 Commons Beanutils 的文档项目中,您可以找到所需的说明:
The Java language provides Reflection and Introspection APIs (see the
java.lang.reflect
andjava.beans
packages in the JDK Javadocs). However, these APIs can be quite complex to understand and utilize. The BeanUtils component provides easy-to-use wrappers around these capabilities.
您可以轻松地自己完成:
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);
}
关于java - 私有(private)构造函数不影响 Dozer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35124628/