如何将泛型接口传递给经过验证的方法?

时间:2018-12-18 15:09:06

标签: java generics reification

我有一个通用接口

public interface MyInterface<T> {
    T method(T input);
}

及其一些实现,例如通过普通的类

public class MyClass<T> implements MyInterface<T> {
    @Override
    public T method(T input) {
        T output = input; // whatever
        return output;
    }
}

和匿名类(请参见下文)。现在,我要测试这些实现:

class TestClass1 {
    // ...
}

class TestClass2 {
    final int n;
    final String s;

    TestClass2(int n, String s) {
        this.n = n;
        this.s = s;
    }
    // ...
}

public class TestGenericImplementation {
    private static <T> void makeTest(T testObject, MyInterface<T> impl) {
        T output = impl.method(testObject);
        if (output == null)
            throw new NullPointerException();
        // verify output further
    }

    // Question 1. How to specify the parameter here properly?
    public static void testImplementation(MyInterface impl) {
        // Question 2. How to avoid compiler warning about unchecked cast below?

        // Doesn't work if impl is of type MyInterface<?> above
        makeTest(new TestClass1(), impl);
        makeTest(new TestClass2(1, "ABC"), impl); 

        // Ugly typecasts. Compiler complains.
        makeTest(new TestClass1(), (MyInterface<TestClass1>) impl);  
        makeTest(new TestClass2(1, "ABC"), (MyInterface<TestClass2>) impl); 
    }

    public static void main(String[] args) {
        // Question 3. How to pass the interface argument here?

        // Works but issues compiler warning about raw type
        testImplementation(new MyClass());
        testImplementation(new MyInterface() {
            @Override
            public Object method(Object input) {
                return null; // whatever
            }
        });

        // Looks ugly
        testImplementation(new MyClass<Object>()); 
        testImplementation(new MyInterface<Object>() {
            @Override
            public Object method(Object input) {
                return null;
            }
        });

        /* Diamond operator appeared only in Java 7,
         * while generics were introduced in Java 5.
         * What was the recommended way to solve this problem between 2004 and 2011?
         * Besides that, this doesn't work for anonymous classes.
         */
        testImplementation(new MyClass<>()); 
        testImplementation(new MyInterface<>() { // Doesn't work
            @Override
            public Object method(Object input) {
                return null;
            }
        });

        testImplementation(x -> x); // Lambda exprssions are for simple cases only
    }
}

问题在于,由于从通用接口过渡到其版本化版本,编译器发出了一系列错误和警告(我需要在适当的位置使用具体的类TestClass1TestClass2进行编译)通用类型变量T的名称。是否可以完全避免这些警告?如果不是(即只能将其抑制),是否有由此引起的陷阱?

2 个答案:

答案 0 :(得分:0)

<T> void makeTest(T testObject, Test.MyInterface<T> impl)

期望两个参数的T相同。

public static void testImplementation(Test.MyInterface impl) {
    makeTest(new Test.TestClass1(), impl);
    makeTest(new Test.TestClass2(1, "ABC"), impl);
    //...

这是一个矛盾。在第一种情况下,T将为TestClass1,在第二种情况下,其为TestClass2。如果要使用Test.MyInterface的通用版本,则没有任何类型可以满足它。您只是因为使用原始类型而摆脱了这一麻烦。不能同时是Test.MyInterface<TestClass1>Test.MyInterface<TestClass2>

您需要摆脱testImplementation方法并停止使用原始类型。您的main方法的第一部分可能如下所示:

public static void main(String[] args) {

    makeTest(new Test.TestClass1(), new Test.MyClass<>());
    makeTest(new Test.TestClass2(1, "ABC"), new Test.MyClass<>());

答案 1 :(得分:0)

这就是我解决问题的方式。

/* This utility method bears the brunt.
 * It shows that the cast is safe for this particular interface.
 * It is recommended to explain why. Example is given below. */
@SuppressWarnings("unchecked")
public static <T> MyInterface<T> reify(MyInterface<?> impl) {
    /* Safe because instances of MyInterface<T> doesn't suppose to hold
     * objects of type T (directly or indirectly) between invocations
     * of its methods. */
    return (MyInterface<T>) impl;
}

// Use a wildcard type in the signature
public static void testImplementation(MyInterface<?> impl) {
    // No warnings now
    makeTest(new TestClass1(), reify(impl));
    makeTest(new TestClass2(1, "ABC"), reify(impl));
}

public static void main(String[] args) {
    // Use the diamond operator for ordinary classes
    testImplementation(new MyClass<>());
    // Use lambda expressions when possible
    testImplementation(x -> x);
    /* Anonymous classes still require explicit type
    (Object in this case, Bound when the type variable is bounded
    at the interface definition: MyInterface<T extends Bound> */
    testImplementation(new MyInterface<Object>() {
        @Override
        public Object method(Object input) {
            return input;
        }
    });
}

仍然需要一个@SuppressWarnings,但将所有不安全的操作集中在一个地方,在此要解释为什么抑制是安全的。

如果有人有更好的解决方案,请告诉我。