Skip to content
Advertisement

Factory pattern using generics

I would like to build a class that caches classes of type CachedObject using Map.

JavaScript

Below is the factory class.

JavaScript

I have a class that extends CacheableObject as below:

JavaScript

When I try to create an instance of class X that extends CachedObject using the get method in the factory as below: (please note that cachedObjectFactory is autowired using Spring)

JavaScript

I get the compile time error “The method get(Class, Long) in the type CachedObjectFactory is not applicable for the arguments (Class, Long)”. How should I instantiate an object X using the factory method?

Advertisement

Answer

Declaring a field as CachedObjectFactory<CachedObject> doesn’t really mean anything — the parameter already has CachedObject as an upper bound.

You can get your code to compile by changing you factory to look like this:

JavaScript

As you are using your factory for many classes, making it generic doesn’t really make sense.

Of course if two instances of different subclasses of CachedObject have the same id you’ll get a runtime ClassCastException.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement