Class 将对象添加到 Apache 池时抛出异常

Class Cast Exception while adding Objects to Apache Pool

我正在尝试弄清楚如何实施 Apache Pool 2(我使用的是 2.5)。作为初始 POC,我创建了一个包含 firstName、lastName、employeeId 和 age 的 Employee 对象(观察者模式)。我创建了一个实现 PooledObjectFactory 的 EmployeeObjectFactory,并且在主要 class 中我试图添加 Employee class 的对象。但是我得到了一个 class 转换异常(EmployeeObjects 不能转换为 PooledObjects)。那么我需要对我的 EmployeeObject 进行哪些更改?

员工Class

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
}

主要Class

public static void main(String arg[]) throws Exception {
GenericObjectPool employeeObjectPool = new GenericObjectPool(new EmployeeObjectFactory());
employeeObjectPool.addObject(); 

我尝试添加尽可能少的代码,因为即使是我也讨厌浏览大量代码。任何帮助将不胜感激。

看完Apache Docs终于找到答案了。 DefaultPooledObject 是我需要使用的。 DefaultPooledObject - “创建一个包装所提供对象的新实例,以便池可以跟踪池化对象的状态。”在 makeObject() 函数中,我返回了一个 DefaultPooledObject。所以我的代码看起来像

@Override
public PooledObject<EmployeeObject> makeObject() {
 return new DefaultPooledObject<>(new EmployeeObject.Builder().build());
}