【问题标题】:Class Cast Exception while adding Objects to Apache Pool将对象添加到 Apache 池时发生类转换异常
【发布时间】: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&lt;EmployeeObject&gt;吗?为什么ClassCastException 会让你大吃一惊?

标签: java apache pool


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多