Javaのジェネリクスの使い方で質問があります。Base<T>のTの型に応じて処理を以下のように振り分けたいです。
Java
1public class Base<T> { 2 public Base() {} 3} 4 5~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 6 7public class HelloWorld{ 8 9 public static void main(String []args){ 10 Base[] bases = new Base[] { 11 new Base<Integer>(), 12 new Base<Long>(), 13 new Base<Float>() 14 }; 15 16 for (Base base : bases) { 17 if (base instanceof Base<Integer>) { 18 // T=Integer の場合 19 method((Base<Integer>) base); 20 } else if (base instanceof Base<Long>) { 21 // T=Long の場合 22 method((Base<Long>) base); 23 } else { 24 // T=その他の場合 25 method(base); 26 } 27 } 28 } 29 30 public static void method(Base<Integer> baseInteger) { 31 System.out.println("method(Base<Integer> baseInteger)"); 32 33 } 34 public static void method(Base<Long> baseLong) { 35 System.out.println("method(Base<Long> baseLong)"); 36 37 } 38 public static void method(Base base) { 39 System.out.println("method(Base base)"); 40 41 } 42}
もちろんコンパイルエラーとなるのですが(下記参照)、どのようにすれば実現できるでしょうか?また、そもそもの話ですが、Tの型い応じて処理を振り分けるというのは、ジェネリクスの使い方として正しいのでしょうか?
sh-4.3$ javac HelloWorld.java HelloWorld.java:26: error: name clash: method(Base<Long>) and method(Base<Integer>) have the same erasure public static void method(Base<Long> baseLong) { ^ HelloWorld.java:30: error: name clash: method(Base) and method(Base<Integer>) have the same erasure public static void method(Base base) { ^ HelloWorld.java:12: error: illegal generic type for instanceof if (base instanceof Base<Integer>) { ^ HelloWorld.java:14: error: illegal generic type for instanceof } else if (base instanceof Base<Long>) { ^ Note: HelloWorld.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 4 errors
コンパイルはコチラのサイトで行いました。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/11 16:09