javaのenum(列挙型)には、enumクラス全体で定義したメソッドを各定数でoverrideすることができるという機能があります。 Effective Java 第6章項目30 に定数固有メソッド実装(constant-specific method implementation)として紹介されています。
TestEnumClassName.java
のMethod#getAltName
のようなメソッドを想定したとします。
Method.class.getSimpleName()
で得られる文字列(クラス名)と定数名を連結させた文字列を取得する、
というのがこのメソッドの期待する振る舞いですが、定数固有メソッド実装をしているPOST
/PUT
では想定した振る舞いをしません。
実行結果
GET alt name: Method#GET
GET class#getName(): Method
GET class#getSimpleName(): Method
GET class#getCanonicalName(): Method
-------
POST alt name: #POST
POST class#getName(): Method$1
POST class#getSimpleName():
POST class#getCanonicalName(): null
-------
PUT alt name: #PUT
PUT class#getName(): Method$2
PUT class#getSimpleName():
PUT class#getCanonicalName(): null
-------
DELETE alt name: Method#DELETE
DELETE class#getName(): Method
DELETE class#getSimpleName(): Method
DELETE class#getCanonicalName(): Method
TestEnumClassName.java
のようなファイルをコンパイルすると、
- TestEnumClassName.class
- Method.class
- Method$1.class
- Method$2.class
というクラスファイルが生成されます。
Method$1.class
をデコンパイルするとMethod
クラスを継承したクラスが生成されていることがわかります。
定数固有メソッドを実装したenum定数は新しくクラスを生成するため注意が必要です。