I am trying to implement a factory pattern whereby given an object with a type field, I can dynamically get the class to process that object
Here is a simplified example of what I have so far. Basically, There are a series of Spring Service components which implement the Builder interface. They define the TYPE that they can handle. The Factory class will have builders injected by Spring i.e. all the classes that implement Builder interface.
The Test class is illustrating how that would be used i.e. the parameter to test will have a type field which is used as a lookup to get the correct builder class.
This works ok however I get a lot of Raw type warnings which I am not sure the best way to get rid of.
Is there a better way to go with this?
Thanks!
#Service
public class Factory {
// Raw type warning here
Map<Builder.TYPE, Builder> builderMap;
// Raw type warning here
public Factory(List<Builder> builders){
builderMap = builders.stream().collect(Collectors.toMap( Builder::getType, Function.identity() ));
}
// Raw type warning here
public Builder getBuilder(Builder.TYPE TYPE){
return builderMap.get(TYPE);
}
public interface Builder<T> {
TYPE getType();
ProcessedObject process(T object);
enum TYPE {
ONE
}
}
#Service
public class TestBuilder implements Builder<DtoOne> {
#Override
public TYPE getType() {
return TYPE.ONE;
}
#Override
public ProcessedObject process(DtoOne object) {
// ... process
}
}
#Service
public class Test {
private final Factory factory; // omitting constructor code
public void test(Dto testObject) {
// Raw type warning here
Builder builder = factory.getBuilder(testObject.getType());
// Raw type warning here
builder.process(testObject);
}
}
Updating answer based on comment below:
If I understood correctly, basically you want to use T to restrict the object type in process() method argument.
I can think of two approaches:
If you have BaseDto which all other Dto objects (DtoOne, DtoTwo etc.) extend, we can write the code as below.
Builder:
public interface Builder<T extends BaseDto> {
TYPE getType();
Object process(T object);
enum TYPE {
ONE
}
}
Factory:
public class Factory<T extends BaseDto> {
Map<Builder.TYPE, Builder<T>> builderMap;
public Factory(List<Builder<T>> builders){
builderMap = builders.stream().collect(Collectors.toMap( Builder::getType, Function.identity() ));
}
public Builder<T> getBuilder(Builder.TYPE TYPE){
return builderMap.get(TYPE);
}
}
That way we can avoid raw type warnings.
If there is no common base class, then we can pretty much add any type to a builder which is essentially an unknown type (can be anything). In that case we can replace raw type warnings with wildcard as below.
Builder class will remain same. Factory class would look like below:
public class Factory {
Map<Builder.TYPE, Builder<?>> builderMap;
public Factory(List<Builder<?>> builders){
builderMap = builders.stream().collect(Collectors.toMap( Builder::getType, Function.identity() ));
}
public Builder<?> getBuilder(Builder.TYPE TYPE){
return builderMap.get(TYPE);
}
}
I have following hierarchy of classes:
public interface Table<V> {
Map<String, Object> getNamedParams(SearchQuery<V> query);
}
public class TopicTable implements Table<Topic> {
#Override
public Map<String, Object> getNamedParams(TopicSearchQuery query) {
// TODO to be implemented
return null;
}
}
#Data
public abstract class SearchQuery<E> {
private Integer pageSize;
private Integer pageNumber;
}
public class TopicSearchQuery extends SearchQuery<Topic> {
private String orgId;
private Boolean isShared;
private String name;
private String description;
}
My IDE is complaining that the method getNamedParams from interface Table is not properly implemented in class TopicTable. I know it has something to do with inheritance and my usage of generics.
What I am trying to accomplish: tie entity, search query and table together, so that table operates only with proper entities and search queries. I want this to be cohesive and robust. Any idea on how I can achieve it best, so that the design is not cluttered or cumbersome, ideally, with no explicit casting.
Thanks in advance.
This method signature:
getNamedParams(TopicSearchQuery query)
Does not override the method. It would have to be:
getNamedParams(SearchQuery<Topic> query)
You can't change the type of the parameter to be any more specific (because this would violate Liskov substitutability) or less specific (because Java doesn't allow it when overriding) than required by the interface.
If you want to be able to require a more specific parameter type, add another type variable:
public interface Table<V, SQ extends SearchQuery<V>> {
Map<String, Object> getNamedParams(SQ query);
}
Then you can declare your implementing class to use that type:
public class TopicTable implements Table<Topic, TopicSearchQuery> {
#Override
public Map<String, Object> getNamedParams(TopicSearchQuery query)
The Java documentation for wildcards says that they can be used as return types but it is generally not a good idea. Is this still true if the wildcard is used as the return type for an abstract method but the class that implements this method returns a concrete type? If not, what is the best way to handle this type of situation. Consider the example below. In this case, Entity might be modeled after a JSON REST response, where in the second case the result is just a list of Strings. Is it better to use List<Object> as the return type or something else entirely?
public abstract class AbstractClient {
public abstract List<?> listEntities();
}
public class ConcreteClient {
#Override
public List<Entity> listEntities();
}
public class ConcreteClient2 {
#Override
public List<String> listEntities();
}
In such a case it is better to use generics properly instead of using wildcards. Use a type parameter and extend the abstract class with the appropriate argument for the type parameter:
public abstract class AbstractClient<T> {
public abstract List<T> listEntities();
}
public class ConcreteClient extends AbstractClient<Entity> {
#Override
public List<Entity> listEntities();
}
public class ConcreteClient2 extends AbstractClient<String> {
#Override
public List<String> listEntities();
}
I have the following class hierarchy:
public abstract class Config<T> implements Proxy<T> {
public abstract T parse();
public T get() {....}
}
public class IntegerConfig<Integer> extends Config<Integer> {
public Integer parse() {...}
}
public class LongConfig<Long> extends Config<Long> {
public Long parse() {...}
}
public class IntegerListConfig<List<Integer>> extends Config<List<Integer>> {
public List<Integer> parse() {....}
}
And so on...
I'd like to introduce a new class:
public class ConfigMutation<T> implements Proxy<T> {
public ConfigMutation(....) {
//// create a concrete implementation of Config<T> according to actual parameterized type
}
}
Essentially, I'd like to avoid repeating the entire class hierarchy of Config, and support in ConfigMutation all types that have parameterized implementations in Config class hierarchy.
Couldn't find a way to do it. (Class<T>)((ParameterizedType)getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0] obviously returns T, and not the actual type.
Also, once this problem is solved, I'd be happy if someone could suggest some factory pattern with generic types, so when I'm instantiating a Config derived class inside ConfigMutation, I wouldn't have to do it with a huge if...else block on actual type.
Thanks,
Lior
Change your ConfigMutation class to :
public class ConfigMutation<U,T extends Config<U>> implements Proxy<U> {
public ConfigMutation() {
}
}
You can then use ConfigMutation as :
ConfigMutation<Integer,IntegerConfig> mutation;
You won't be able to do something as follows which is what you want :
ConfigMutation<String,IntegerConfig> mutation;
That said, there is a change you need to make to your concrete Config implementers as well. For example, change IntegerConfig to :
public class IntegerConfig extends Config<Integer> {
public Integer parse() {...}
}
The Integer in IntegerConfig<Integer> will be considered as a type parameter and not the Integer class which is not what you want. (An IDE should give you a warning for this; The type parameter Integer is hiding the type Integer)
I wanted to write a Converter for JPA that stores any enum as UPPERCASE. Some enums we encounter do not follow yet the convention to use only Uppercase letters so until they are refactored I still store the future value.
What I got so far:
package student;
public enum StudentState {
Started,
Mentoring,
Repeating,
STUPID,
GENIUS;
}
I want "Started" to be stored as "STARTED" and so on.
package student;
import jpa.EnumUppercaseConverter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "STUDENTS")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long mId;
#Column(name = "LAST_NAME", length = 35)
private String mLastName;
#Column(name = "FIRST_NAME", nullable = false, length = 35)
private String mFirstName;
#Column(name = "BIRTH_DATE", nullable = false)
#Temporal(TemporalType.DATE)
private Date mBirthDate;
#Column(name = "STUDENT_STATE")
#Enumerated(EnumType.STRING)
#Convert(converter = EnumUppercaseConverter.class)
private StudentState studentState;
}
the converter currently looks like this:
package jpa;
import javax.persistence.AttributeConverter;
import java.util.EnumSet;
public class EnumUppercaseConverter<E extends Enum<E>> implements AttributeConverter<E, String> {
private Class<E> enumClass;
#Override
public String convertToDatabaseColumn(E e) {
return e.name().toUpperCase();
}
#Override
public E convertToEntityAttribute(String s) {
// which enum is it?
for (E en : EnumSet.allOf(enumClass)) {
if (en.name().equalsIgnoreCase(s)) {
return en;
}
}
return null;
}
}
what will not work is that I do not know what enumClass will be at runtime. And I could not figure out a way to pass this information to the converter in the #Converter annotation.
So is there a way to add parameters to the converter or cheat a bit? Or is there another way?
I'm using EclipseLink 2.4.2
Thanks!
Based on #scottb solution I made this, tested against hibernate 4.3: (no hibernate classes, should run on JPA just fine)
Interface enum must implement:
public interface PersistableEnum<T> {
public T getValue();
}
Base abstract converter:
#Converter
public abstract class AbstractEnumConverter<T extends Enum<T> & PersistableEnum<E>, E> implements AttributeConverter<T, E> {
private final Class<T> clazz;
public AbstractEnumConverter(Class<T> clazz) {
this.clazz = clazz;
}
#Override
public E convertToDatabaseColumn(T attribute) {
return attribute != null ? attribute.getValue() : null;
}
#Override
public T convertToEntityAttribute(E dbData) {
T[] enums = clazz.getEnumConstants();
for (T e : enums) {
if (e.getValue().equals(dbData)) {
return e;
}
}
throw new UnsupportedOperationException();
}
}
You must create a converter class for each enum, I find it easier to create static class inside the enum: (jpa/hibernate could just provide the interface for the enum, oh well...)
public enum IndOrientation implements PersistableEnum<String> {
LANDSCAPE("L"), PORTRAIT("P");
private final String value;
#Override
public String getValue() {
return value;
}
private IndOrientation(String value) {
this.value= value;
}
public static class Converter extends AbstractEnumConverter<IndOrientation, String> {
public Converter() {
super(IndOrientation.class);
}
}
}
And mapping example with annotation:
...
#Convert(converter = IndOrientation.Converter.class)
private IndOrientation indOrientation;
...
With some changes you can create a IntegerEnum interface and generify for that.
What you need to do is write a generic base class and then extend that for each enum type you want to persist. Then use the extended type in the #Converter annotation:
public abstract class GenericEnumUppercaseConverter<E extends Enum<E>> implements AttributeConverter<E, String> {
...
}
public FooConverter
extends GenericEnumUppercaseConverter<Foo>
implements AttributeConverter<Foo, String> // See Bug HHH-8854
{
public FooConverter() {
super(Foo.class);
}
}
where Foo is the enum you want to handle.
The alternative would be to define a custom annotation, patch the JPA provider to recognize this annotation. That way, you could examine the field type as you build the mapping information and feed the necessary enum type into a purely generic converter.
Related:
https://hibernate.atlassian.net/browse/HHH-8854
This answer has been modified to take advantage of default interface methods in Java 8.
The number of components of the facility (enumerated below) remains at four, but the amount of required boilerplate is much less. The erstwhile AbstractEnumConverter class has been replaced by an interface named JpaEnumConverter which now extends the JPA AttributeConverter interface. Moreover, each placeholder JPA #Converter class now only requires the implementation of a single abstract method that returns the Class<E> object for the enum (for even less boilerplate).
This solution is similar to others and also makes use of the JPA Converter facility introduced in JPA 2.1. As generic types in Java 8 are not reified, there does not appear to be an easy way to avoid writing a separate placeholder class for each Java enum that you want to be able to convert to/from a database format.
You can however reduce the process of writing an enum converter class to pure boilerplate. The components of this solution are:
Encodable interface; the contract for an enum class that grants access to a String token for each enum constant. This is written only once and is implemented by all enum classes that are to be persisted via JPA. This interface also contains a static factory method for getting back the enum constant for its matching token.
JpaEnumConverter interface; provides the common code for translating tokens to/from enum constants. This is also only written once and is implemented by all the placeholder #Converter classes in the project.
Each Java enum class in the project implements the Encodable interface.
Each JPA placeholder #Converter class implements the JpaEnumConverter interface.
The Encodable interface is simple and contains a static factory method, forToken(), for obtaining enum constants:
public interface Encodable{
String token();
public static <E extends Enum<E> & Encodable> E forToken(Class<E> cls, String tok) {
final String t = tok.trim();
return Stream.of(cls.getEnumConstants())
.filter(e -> e.token().equalsIgnoreCase(t))
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Unknown token '" +
tok + "' for enum " + cls.getName()));
}
}
The JpaEnumConverter interface is a generic interface that is also simple. It extends the JPA 2.1 AttributeConverter interface and implements its methods for translating back and forth between entity and database. These are then inherited by each of the JPA #Converter classes. The only abstract method that each placeholder class must implement, is the one that returns the Class<E> object for the enum.
public interface JpaEnumConverter<E extends Enum<E> & Encodable>
extends AttributeConverter<E, String> {
public abstract Class<E> getEnumClass();
#Override
public default String convertToDatabaseColumn(E attribute) {
return (attribute == null)
? null
: attribute.token();
}
#Override
public default E convertToEntityAttribute(String dbData) {
return (dbData == null)
? null
: Encodeable.forToken(getEnumClass(), dbData);
}
}
An example of a concrete enum class that could now be persisted to a database with the JPA 2.1 Converter facility is shown below (note that it implements Encodable, and that the token for each enum constant is defined as a private field):
public enum GenderCode implements Encodable{
MALE ("M"),
FEMALE ("F"),
OTHER ("O");
final String e_token;
GenderCode(String v) {
this.e_token = v;
}
#Override
public String token() { // the only abstract method of Encodable
return this.e_token;
}
}
The boilerplate for every placeholder JPA 2.1 #Converter class would now look like the code below. Note that every such converter will need to implement JpaEnumConverter and provide the implementation for getEnumClass() ... and that's all! The implementations for the JPA AttributeConverter interface methods are inherited.
#Converter
public class GenderCodeConverter
implements JpaEnumConverter<GenderCode> {
#Override
public Class<GenderCode> getEnumClass() { // sole abstract method
return GenderCode.class;
}
}
These placeholder #Converter classes can be readily nested as static member classes of their associated enum classes.
The above solutions are really fine. My small additions here.
I also added the following to enforce when implementing the interface writing a converter class. When you forget jpa starts using default mechanisms which are really fuzzy solutions (especially when mapping to some number value, which I always do).
The interface class looks like this:
public interface PersistedEnum<E extends Enum<E> & PersistedEnum<E>> {
int getCode();
Class<? extends PersistedEnumConverter<E>> getConverterClass();
}
With the PersistedEnumConverter similar to previous posts. However when the implementing this interface you have to deal with the getConverterClass implementation, which is, besides being an enforcement to provide the specific converter class, completely useless.
Here is an example implementation:
public enum Status implements PersistedEnum<Status> {
...
#javax.persistence.Converter(autoApply = true)
static class Converter extends PersistedEnumConverter<Status> {
public Converter() {
super(Status.class);
}
}
#Override
public Class<? extends PersistedEnumConverter<Status>> getConverterClass() {
return Converter.class;
}
...
}
And what I do in the database is always make a companion table per enum with a row per enum value
create table e_status
(
id int
constraint pk_status primary key,
label varchar(100)
);
insert into e_status
values (0, 'Status1');
insert into e_status
values (1, 'Status2');
insert into e_status
values (5, 'Status3');
and put a fk constraint from wherever the enum type is used. Like this the usage of correct enum values is always guaranteed. I especially put values 0, 1 and 5 here to show how flexible it is, and still solid.
create table using_table
(
...
status int not null
constraint using_table_status_fk references e_status,
...
);
I found a way to do this without using java.lang.Class, default methods or reflection. I did this by using a Function that is passed to the Convertor in the constructor from the enum, using method reference. Also, the Convertos from the enum should be private, no need for them outside.
Interface that Enums should implement in order to be persisted
public interface PersistableEnum<T> {
/** A mapping from an enum value to a type T (usually a String, Integer etc).*/
T getCode();
}
The abstract converter will use a Function in order to cover convertToEntityAttribute transformation
#Converter
public abstract class AbstractEnumConverter<E extends Enum<E> & PersistableEnum<T>, T> implements AttributeConverter<E, T> {
private Function<T, E> fromCodeToEnum;
protected AbstractEnumConverter(Function<T, E> fromCodeToEnum) {
this.fromCodeToEnum = fromCodeToEnum;
}
#Override
public T convertToDatabaseColumn(E persistableEnum) {
return persistableEnum == null ? null : persistableEnum.getCode();
}
#Override
public E convertToEntityAttribute(T code) {
return code == null ? null : fromCodeToEnum.apply(code);
}
}
The enum will implement the interface (I am using lombok for the getter) and create the converted by using a constructor
that receives a Function, I pass the ofCode using method reference. I prefer this instead of working with java.lang.Class or using reflection, I have more freedom in the enums.
#Getter
public enum CarType implements PersistableEnum<String> {
DACIA("dacia"),
FORD("ford"),
BMW("bmw");
public static CarType ofCode(String code) {
return Arrays.stream(values())
.filter(carType -> carType.code.equalsIgnoreCase(code))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Invalid car type code."));
}
private final String code;
CarType(String code) {
this.code = code;
}
#Converter(autoApply = true)
private static class CarTypeConverter extends AbstractEnumConverter<CarType, String> {
protected CarTypeConverter () {
super(CarType::ofCode);
}
}
}
4.In the entity you just have to use the enum type and it will save it's String code.
#Column(name = "CAR_TYPE")
private CarType workflowType;
If you don't mind reflection, this works. Credit to another SO answer inline.
abstract class EnumTypeConverter<EnumType,ValueType> implements AttributeConverter<EnumType, ValueType> {
private EnumType[] values
#Override
ValueType convertToDatabaseColumn(EnumType enumInstance) {
return enumInstance ? enumInstance.getProperty(getValueColumnName()) : null
}
#Override
EnumType convertToEntityAttribute(ValueType dbData) {
if(dbData == null){
return null
}
EnumType[] values = getValues()
EnumType rtn = values.find {
it.getProperty(getValueColumnName()).equals(dbData)
}
if(!rtn) {
throw new IllegalArgumentException("Unknown ${values.first().class.name} value: ${dbData}")
}
rtn
}
private EnumType[] getValues() {
if(values == null){
Class cls = getTypeParameterType(getClass(), EnumTypeConverter.class, 0)
Method m = cls.getMethod("values")
values = m.invoke(null) as EnumType[]
}
values
}
abstract String getValueColumnName()
// https://stackoverflow.com/a/59205754/3307720
private static Class<?> getTypeParameterType(Class<?> subClass, Class<?> superClass, int typeParameterIndex) {
return getTypeVariableType(subClass, superClass.getTypeParameters()[typeParameterIndex])
}
private static Class<?> getTypeVariableType(Class<?> subClass, TypeVariable<?> typeVariable) {
Map<TypeVariable<?>, Type> subMap = new HashMap<>()
Class<?> superClass
while ((superClass = subClass.getSuperclass()) != null) {
Map<TypeVariable<?>, Type> superMap = new HashMap<>()
Type superGeneric = subClass.getGenericSuperclass()
if (superGeneric instanceof ParameterizedType) {
TypeVariable<?>[] typeParams = superClass.getTypeParameters()
Type[] actualTypeArgs = ((ParameterizedType) superGeneric).getActualTypeArguments()
for (int i = 0; i < typeParams.length; i++) {
Type actualType = actualTypeArgs[i]
if (actualType instanceof TypeVariable) {
actualType = subMap.get(actualType)
}
if (typeVariable == typeParams[i]) return (Class<?>) actualType
superMap.put(typeParams[i], actualType)
}
}
subClass = superClass
subMap = superMap
}
return null
}
}
Then in the entity class:
enum Type {
ATYPE("A"), ANOTHER_TYPE("B")
final String name
private Type(String nm) {
name = nm
}
}
...
#Column
Type type
...
#Converter(autoApply = true)
static class TypeConverter extends EnumTypeConverter<Type,String> {
String getValueColumnName(){
"name"
}
}
This is written in groovy, so you'll need some adjustments for Java.