[英]Java generics type
考慮下面的代碼...
public class Test {
public interface I {}
public enum E1 implements I {M, N}
public enum E2 implements I {O, P}
public static class A<T extends Enum<T> & I> {
void test() {
// how to print the enum constants here ?
System.out.println("... ");
}
}
public static class B extends A<E2> {}
public static void main(final String[] args) {
A<E1> a = new A<E1>();
B b = new B();
a.test();
b.test();
}
}
如何在test
訪問T
類? 例如,如何打印枚舉常量?
不幸的是,情況A的那些一般信息在運行時不可用。 您必須使用類型標記模式。 如果是B,則可以使用“ hack”來獲取常量:
void test() {
Type superclass = this.getClass().getGenericSuperclass();
if (ParameterizedType.class.isAssignableFrom(superclass.getClass())) {
ParameterizedType genericSuperclass = (ParameterizedType) superclass;
Class enumClass = (Class) genericSuperclass.getActualTypeArguments()[0];
for (Object o : enumClass.getEnumConstants()) {
System.out.println(o);
}
}
}
考慮如何在不使用泛型的情況下編寫程序很有幫助。 可以通過泛型編寫的任何程序也可以通過簡單地刪除類型參數並在適當的位置插入強制類型轉換而變成沒有泛型的等效程序。 (忽略了一些類的元數據中的泛型之類的東西,在這里不相關。)這稱為類型擦除 。
public class Test {
public interface I {}
public enum E1 implements I {M, N}
public enum E2 implements I {O, P}
public static class A {
void test() {
// how to print the enum constants here ?
System.out.println("... ");
}
}
public static class B extends A {}
public static void main(final String[] args) {
A a = new A();
B b = new B();
a.test();
b.test();
}
}
如果沒有泛型就無法編寫程序,那么也不能使用泛型來編寫程序。
是否有理由創建類型參數化類型,然后不使用參數化類型? 使用參數化類型並查看java.lang.Class
的javadoc,它很容易實現,這是一種實現方法。
public class Test {
public interface I { }
public enum E1 implements I {M, N}
public enum E2 implements I {O, P}
public static class A<T extends Enum<T> & I> {
void test(Class<T> ct) {
for(T t: ct.getEnumConstants()) {
System.out.println("... " + t);
}
}
}
public static class B extends A<E2> {}
public static void main(final String[] args) {
A<E1> a = new A<E1>();
B b = new B();
System.out.println("Using E1");
a.test(E1.class);
System.out.println("Using E2");
b.test(E2.class);
}
}
產量
Using E1
... M
... N
Using E2
... O
... P
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.