【发布时间】:2018-02-06 16:52:28
【问题描述】:
我正在尝试弄清楚如何实现 Apache Pool 2(我使用的是 2.5)。作为初始 POC,我创建了一个包含 firstName、lastName、employeeId 和 age(观察者模式)的 Employee 对象。我创建了一个实现 PooledObjectFactory 的 EmployeeObjectFactory,并且在主类中我试图添加 Employee 类的对象。但我得到一个类转换异常(EmployeeObjects 不能转换为 PooledObjects)。那么我需要对 EmployeeObjects 进行哪些更改?
员工类
public class Employee{
private String firstName;
// omitting the getters and setters for other fields
public static class Builder {
private String firstName = "Unsub";
// declared and initialized lastName, emailId and age
public Builder firstName(String val) {
firstName = val;
return this;
}
// Similarly for other values
public EmployeeObject build() {
return new EmployeeObject(this);
}
}
private EmployeeObject(Builder builder) {
firstName = builder.firstName;
// omitting rest of the code
}
}
在 EmployeeObjectFactory 中
public class EmployeeObjectFactory implements PooledObjectFactory<EmployeeObject> {
@Override
public PooledObject<EmployeeObject> makeObject() {
return (PooledObject<EmployeeObject>) new EmployeeObject.Builder().build(); // This is where I'm getting the class cast
}
// Omitting rest of the code
}
主类
public static void main(String arg[]) throws Exception {
GenericObjectPool employeeObjectPool = new GenericObjectPool(new EmployeeObjectFactory());
employeeObjectPool.addObject();
我尝试添加尽可能少的代码,因为即使我也讨厌处理大量代码。任何帮助将不胜感激。
【问题讨论】:
-
EmployeeObject.Builder.build()返回EmployeeObject。那应该分配给PooledObject<EmployeeObject>吗?为什么ClassCastException会让你大吃一惊?