简体   繁体   中英

Use generics as an argument and access methods of particular enums

I am doing a web application and I have several Enum to set the values ​​of the dropdown of views (5 and counting ...)

The format of the Enums is the same:

public enum PetType {
    CAT ("Cat"),
    DOG ("Dog");

    private String type;

    PetType(String type) { this.type = type; }

    public void   setType(String type) { this.type = type; }
    public String getType()            { return this.type; }

}

I also use a DTO called OptionDTO to take these values ​​and bring them to view:

public class OptionDTO {
    private Integer value;
    private String option;

    / * Constructors, getters and setters * /

}

In the service I am creating an OptionDTO list from the Enum s:

public List<OptionDTO> getPetTypes() {

    List<OptionDTO> l = new ArrayList<>();

   for (PetType p: PetType.values​​())
       l.add (new OptionDTO(p.ordinal(), p.getType()));

   return l;
}

What I would like to implement is a private method that returns List <OptionDTO> . For example

public List<OptionDTO> getPetTypes() {
    return getList(PetType.values​​());
}

I am trying to use Generics but I have problems when I want to use the getType() method.

private<T extends Enum<T>> List<OptionDTO> getList(T[] list) {
    List<OptionDTO> l = new ArrayList<>();

    for(T t : list)
        l.add(new OptionDTO(t.ordinal(), t.getType()));

    return l;
}

My questions are:

  1. Is there a way to implement Generics to access the getType () method that is common to all the Enums I have?

  2. Is this the recommended way to address the problem? Because I saw the use of interfaces there.

You would do it like this:

interface HasType {
    String getType();
}
enum PetType implements HasType {
    ...
}
private <E extends Enum<E> & HasType> List<OptionDTO>(E[] values) {
    ...
}

The intersection type Enum<E> & HasType means that E has to be a subtype of both Enum<E> and HasType .

It's also the case that you could pass a Class<E> and use type.getEnumConstants() instead of passing the values() directly, if you ever needed to do that.

As a side note, it doesn't really make sense to give your enum setters. Enums are supposed to be immutable constants.

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