具有内部类和内部接口的Java泛型 [英] Java generics with inner class and inner interface

查看:140
本文介绍了具有内部类和内部接口的Java泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我有一个通用的OuterClass,一个使用OuterClass泛型和
非泛型InnerInterface的InnerClass。

  public class OuterClass< E> {

public class InnerClass {

public E someMethod(){
return null;



public interface InnerInterface {
public void onEvent(OuterClass.InnerClass innerClass);




$ b $ p
$ b在以下主要方法中,我使用两个实例OuterClass,o1参数化,o2参数化。
我的匿名内部类myListener尝试使用外部类(E)的泛型类型。
下面的代码无法编译(Integer i = innerClass.someMethod() - 类型不匹配:无法从Object转换为整数)。

public static void main(String [] args){

OuterClass< Integer> o1 = new OuterClass< Integer>();
OuterClass< String> o2 = new OuterClass< String>();

OuterClass.InnerInterface innerInterface = new OuterClass.InnerInterface(){
@Override
public void onEvent(InnerClass innerClass){
Integer i = innerClass.someMethod() ;
}
};
}
}

我想表达一下,myListener适用于o1,并应使用E = Integer,而不重复(不重复,我在声明o1时已经说过)。这可能吗?



非常感谢!
Faton。

解决方案

内部接口或枚举是隐式静态的,静态成员没有参数化类型参数的外部类。因此 InnerInterface 应该如下所示:

  public interface InnerInterface< E> {
void onEvent(OuterClass< E> .InnerClass innerClass);

$ / code>

注意 E InnerInterface 的参数不是 c> OuterClass


Below I have a generic OuterClass, an InnerClass that use OuterClass generics and non-generic InnerInterface.

public class OuterClass<E> {

    public class InnerClass  {

        public E someMethod() {
            return null;
        }
    }

    public interface InnerInterface{
        public void onEvent(OuterClass.InnerClass innerClass);
    }
}

In the main method below, I use two instance of OuterClass, o1 parameterized with , and o2 with . My annonymous inner class myListener tries to use the generic type of the outer class (E). The code as it is below does not compile (Integer i = innerClass.someMethod() - Type mismatch: cannot convert from Object to Integer).

public class Test {
    public static void main(String[] args) {

        OuterClass<Integer> o1 = new OuterClass<Integer>();
        OuterClass<String> o2 = new OuterClass<String>();

        OuterClass.InnerInterface innerInterface = new OuterClass.InnerInterface() {
            @Override
            public void onEvent(InnerClass innerClass) {
                Integer i = innerClass.someMethod();
            }
        };
    }
}

I would like to express that myListener is for o1, and should use E = Integer, without repeating it (without repeating , I already say it when declaring o1). Is that possible?

Many thanks! Faton.

解决方案

An inner interface or enum is implicitely static, and static members are not parameterized with the type parameters of the outer class. So InnerInterface should look like this:

public interface InnerInterface<E> {
    void onEvent(OuterClass<E>.InnerClass innerClass);
}

Note that the E parameter of InnerInterface is not the same as the E parameter of OuterClass.

这篇关于具有内部类和内部接口的Java泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆