0

以下のような列挙型の 5 つのケースがあります。

public enum Answers{
    A(0), B(1), C(2), D(3), E(4);

    Answers(int code){
        this.code = code;
    }

    protected int code;

    public int getCode(){
        return this.code;
    }
}

それらはすべて、異なる「コード」と列挙子で構成されることを除いて、すべて実質的に同じです。ジェネリックが列挙型の拡張である次のクラスがありますがgetCode()、基本的な列挙型ではなく、列挙型のみにある を使用できるようにする必要があります。

public class test<T extends Enum>{
    public void tester(T e){
        System.out.println(e.getCode()); //I want to be able to do this, 
                                         //however, the basic enum does don't
                                         //have this method, and enums can't extend
                                         //anything.
    }
}

ありがとうございました

4

4 に答える 4

1

それが Enum に追加したい唯一のメソッドである場合は、それを行う必要はありません。すべての Enumordinalには、Enum 内の位置を表す値を返すメソッドが既にあります。この例を見てください

enum Answers{
    A,B,C,D,E;
}

class EnumTest<T extends Enum<T>>{
    public void tester(T e){
        System.out.println(e.ordinal()); 
    }

    public static void main(String[] args) throws Exception {
        EnumTest<Answers> t = new EnumTest<>();
        t.tester(Answers.A);
        t.tester(Answers.B);
        t.tester(Answers.E);
    }
}

出力:

0
1
4
于 2013-11-11T18:25:54.150 に答える