简体   繁体   中英

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM