我将枚举用作类的通用类型参数。问题在于,如果没有显式强制转换,我将无法使用其方法(这必须归因于运行时类型擦除)。
考虑以下:

public enum TaskDetail {
    CAR_WASH(100, 2);

    private int serviceFees;
    //Something else.
    public int getServiceFees() {
        return serviceFees;
    }
}


我在课堂上使用此类型作为:

public class Task<E extends Enum<TaskDetail>> implements Runnable {
    private E taskDetail;

    public Task(E taskDetail) {
        this.setTaskDetail(taskDetail);
    }

    @Override
    public void run() {
        //do something with taskDetail:
        //not able to access methods without explicit cast.
    }

    public static void main(String[] args) {
        Task<TaskDetail> t = new Task<TaskDetail>(TaskDetail.CAR_PAINT);
        t.taskDetail.getServiceFees(); //This is fine.
    }
}


为什么我不能做到这一点?我可能会误以为可能与普通的类类型参数一样。

最佳答案

您不需要Task类中的泛型类型,这很好

public class Task implements Runnable {
    private TaskDetail taskDetail;

    public Task(TaskDetail taskDetail) {
        this.setTaskDetail(taskDetail);
    }

    @Override
    public void run() {

    }

    public static void main(String[] args) {
        Task t = new Task(TaskDetail.CAR_WASH);
        t.taskDetail.getServiceFees(); //This is fine.
    }
}

10-01 23:56