java泛型一嵌套获取class,Java泛型与类和嵌套静态接口

I want to use a generic class inside a nested static interface. My objective is to do something like this:

public class MyClass{

private MyInterface task;

public static interface MyInterface{

void aMethod (T item);

}

}

But I get the error: Cannot make a static reference to the non-static type T. If I do some changes (below) I can use a generic type inside an interface, but I want to avoid this method because it's redundant to write the same class 2 times: one for MyClass and one for MyInterface.

public class MyClass{

private MyInterface task;

public static interface MyInterface{

void aMethod (T item);

}

}

Thanks.

EDIT: I want to do this:

MyClass c = new MyClass ();

c.setInterface (new MyClass.MyInterface (){

@Override

public void aMethod (String s){

...

}

);

or

MyClass c = new MyClass ();

c.setInterface (new MyClass.MyInterface (){

@Override

public void aMethod (AnotherClass s){

...

}

);

解决方案

A static nested class or nested interface (which is always static, by the way) has no relation to its outer class (or interface) apart from namespace nesting and access to private variables.

So, the type parameter of the outer class is not available inside the nested interface in your case, you should define it again. To avoid confusion, I recommend using a different name for this inner parameter.

(As an example in the standard API, look for the interface Map.Entry, nested inside the interface Map, yet has no access to its type parameters and needs to declare them again.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值