Java嵌套genericsType

时间:2016-01-28 22:51:51

标签: java generics

我遇到了一个有趣的问题。请考虑以下代码:

public class GenericsTest
{
    // An interface with a generic type.
    public interface IObject<K>{}

    // An class with a generic type
    public static class ObjectA<K>
    {
        // An inner class without generic type, but implementing the interface with generic Type
        // When adding a genericType to this class, it will popup the warning: 'hiding'
        public class ObjectB implements IObject<K>
        {

        }

        // A getter with the interface as return Type
        public IObject<K> getObjectB()
        {
            return new ObjectB();
        }
    }

    public ObjectA<String> objectA = new ObjectA<String>();

    // This field is yelling for an genericType, though it can't get one because the class doesn't support a generic argument.
    public ObjectB genericObject = (ObjectB)objectA.getObjectB();
}

所以问题是我的IDE抱怨缺少genericObject字段的genericType,我应该在方法中添加SupressWarning注释。 (幸运的是没有代码破解,但仍然很烦人)。

我可以在内部类中添加泛型类型,但它可以隐藏&#39;通用参数,意味着我需要在那里添加SupressWarning注释。

第二个修复方法是使用第二个泛型类型,如&lt; S extends K&gt; 。在这种情况下,我不需要在课堂上注明SupressWarning。虽然当我尝试使用getter时,我的IDE仍在抱怨:

The member type GenericsTest.ObjectA.ObjectB<String> must be qualified with a parameterized type, since it is not static.

所以基本上我不能使用getter,除非我在方法中添加了genericType的参数。

我的问题是,在不将内部类更改为嵌套类的情况下解决此问题的最简洁方法是什么?

1 个答案:

答案 0 :(得分:0)

这是一个没有问题的简短例子:

public class Test
{
    interface K<T> { }

    static class A<T>
    {
        class B implements K<T> { }

        public K<T> getK() { return new B(); }
    }

    A<String> a = new A<String>();
    A<String>.B b = (A<String>.B) a.getK();
}

注意最后一行:

A<String>.B b = (A<String>.B) a.getK();

说实话,我不确定你给出的例子甚至是如何编写的 - 这个类&#39; ObjectB&#39;从主要的GenericsTest&#39;中看不到。范围,它需要以其&#39;为前缀。父母班。