2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

特定のインターフェースを実装したenumだけを受け取れるように型引数を定義する

Posted at
Main.java
package sample;

public class Main {
    
    public static void main(String[] args) throws Exception {
        method(Hoge.HOGE);
        method(Fuga.FUGA); // コンパイルエラー
        method(new Piyo()); // コンパイルエラー
    }
    
    public static <T extends Enum<?> & MyInterface> void method(T t) {}
    
    public static interface MyInterface {}
    public static enum Hoge implements MyInterface {HOGE}
    public static enum Fuga {FUGA}
    public static class Piyo implements MyInterface {};
}

全ての enumjava.lang.Enum のサブクラスになるので、 <T extends Enum<?>> として、 & MyInterface を追加することでインターフェースを限定させられる。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?