如何从参数输入动态转换对象

时间:2016-03-16 07:36:52

标签: casting

我这里有一个班级员工

public class Employee 
{
    property1;
    property2;
    property3;
    property4;
}

和类EmployeeEntity

public class EmployeeEntity
{
    property1;
    property2;
    property5;
    property6;
}

2这些班级不会继承另一个班级

我有这样的服务

EmployeeService
public Employee getEmployee(Long employeeId)
{
    Employee employee = new Employee();
    EmployeeInDatabase employeeInDatabase = employeeDao.findEmployeeById(employeeId);
    employee.setProperty1(employeeInDatabase .getProperty1());
    employee.setProperty2(employeeInDatabase .getProperty2());
    employee.setProperty3(employeeInDatabase .getProperty3());
    employee.setProperty4(employeeInDatabase .getProperty4());
    return employee;
}

public EmployeeEntity getEmployee(Long employeeId)
{
    EmployeeEntity employeeEntity = new EmployeeEntity();
    EmployeeInDatabase employeeInDatabase = employeeDao.findEmployeeById(employeeId);
    employeeEntity .setProperty1(employeeInDatabase .getProperty1());
    employeeEntity .setProperty2(employeeInDatabase .getProperty2());
    employeeEntity .setProperty5(employeeInDatabase .getProperty5());
    employeeEntity .setProperty6(employeeInDatabase .getProperty6());
    return employeeEntity;
}

如你所见,我有很多针对setProperty1()的重复实现,setProperty2()

我怎么能这样试试?

EmployeeConverter

public Object setProperty1AndProperty2(Object employee, EmployeeInDatabase employeeInDatabase)
{
    Object response;
    if(employee instanceof Employee)
    {
        response = (Employee) employee;
    }
    if(employee instanceof EmployeeInDatabase)
    {
        response = (EmployeeInDatabase) employee;
    }
    response.setPropery1(employee.getProperty1());
    response.setPropery2(employee.getProperty2());
}

从那里我们可以使用setProperty1AndProperty2和2个对象Employee,EmployeeEntity。

有没有人有解决方案?谢谢:))

0 个答案:

没有答案