If commons-pool2 can new object with parameter?

745 Views Asked by At

The create method of PooledObjectFactory has no parameter

https://commons.apache.org/proper/commons-pool/api-2.4.2/org/apache/commons/pool2/BasePooledObjectFactory.html#create--

If my Foo class definition is:

public class Foo {
    private String name;

    public Foo(String name) {
        super();
        this.name = name;
    }
}

Can this Foo can be pooled by commons-pool ?

Thank you for any advice

1

There are 1 best solutions below

1
On

Because objects cannot be created by abstract classes, you need to extend BasePooledObjectFactory and implement its abstract methods. By doing this, you can create your own class(for example, FooFactory) which contains a constructor with parameters. After that, you can use your own class to instantiate objects(namely Foo).

Sample Code:

public class FooFactory extends BasePooledObjectFactory<Foo> {
    private String name;
    public FooFactory(String name) {
        this.name = name;
    }
    @Override  
    public Foo create() throws Exception {
        return new Foo(name);
    }
}