Abdu Muhammadal
Abdu Muhammadal

Reputation: 143

How to initialize generic type using Factory Design Pattern in Java Spring?

I need to initialize generic type of the class but I couldn't do it. As far as I did research, factory design pattern is way better to make this generic type initialization but I don't know how.

Here's my generic service;

@Service
public abstract class GaService<Entity extends Ga<? extends Play>, DTO extends GaDTO<? extends PlayDTO>> {

    @Autowired
    protected GaRepository<Entity> repository;

    @Autowired
    protected Mapper<Entity, DTO> mapper;

    public DTO initialize(){
        Entity entity = new Entity();
        repository.save(entity);
        return mapper.toDTO(entity);
    }

As you notice my new Entity() is giving an error and to achieve this, I need to find a way to initialize Entity. How can I achieve this?

Upvotes: 0

Views: 560

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 9658

I see two options here:

First option: define an abstract factory method to be implemented in the concrete classes:

protected abstract Entity newEntity();

Second option: pass the class to the initialize method:

public DTO initialize(Class<Entity> entityClass){
    Entity entity = entityClass.newInstance();
    repository.save(entity);
    return mapper.toDTO(entity);
}

UPDATE: Third option: pass a Supplier the initialize method:

public DTO initialize(Supplier<Entity> newEntity){
    Entity entity = newEntity.get();
    repository.save(entity);
    return mapper.toDTO(entity);
}

Upvotes: 1

Related Questions