【发布时间】:2011-07-09 20:57:27
【问题描述】:
我想在嵌套的静态接口中使用泛型类。我的目标是做这样的事情:
public class MyClass<T>{
private MyInterface task;
public static interface MyInterface{
void aMethod (T item);
}
}
但我收到错误:无法对非静态类型 T 进行静态引用。如果我做了一些更改(如下),我可以在接口内使用泛型类型,但我想避免这种方法,因为它是多余的将同一个类写 2 次:一次用于 MyClass,一次用于 MyInterface。
public class MyClass<T>{
private MyInterface<T> task;
public static interface MyInterface<T>{
void aMethod (T item);
}
}
谢谢。
编辑:我想这样做:
MyClass c = new MyClass<String> ();
c.setInterface (new MyClass.MyInterface (){
@Override
public void aMethod (String s){
...
}
);
或
MyClass c = new MyClass<AnotherClass> ();
c.setInterface (new MyClass.MyInterface (){
@Override
public void aMethod (AnotherClass s){
...
}
);
【问题讨论】:
-
那你又在问什么?
-
我想在嵌套静态接口的方法中使用 MyClass 中指定的泛型类 T。
-
您的嵌套类可能不是泛型的,它可能有多个泛型类型。明确这一点的唯一方法是列出所有类型
标签: java class generics interface