NewCurrentVersionDiffResult

NewCurrentVersionDiffResult

我有一个复杂的方法,该方法返回DiffResult<T, V>的不同实现。我想对实现进行检查,以便调用其方法并声明结果。

// this is ok
DiffResult<MockVersion, String> result = calculator.diff(a, b);

// this is problem
NewCurrentVersionDiffResult<MockVersion, String> newCurrentVersionDiffResult = assertDiffType(result, NewCurrentVersionDiffResult.class);

// this is ok
Assert.assertEquals("expected", newCurrentVersionDiffResult.getNewValue());


NewCurrentVersionDiffResult具有以下标头

public class NewCurrentVersionDiffResult<T extends ProductDataVersion<T>, V> extends DiffResult<T, V>
{ /* ... */ }


我已经试过了

private static <D extends DiffResult<T, V>, T extends ProductDataVersion<T>, V> D assertDiffType(final DiffResult<T, V> result, final Class<D> type)
{
    Assert.assertThat(result, CoreMatchers.instanceOf(type));
    return type.cast(result);
}


在执行时有效,但会报告编译警告

[WARNING] VersionDiffCalculatorTest.java:[34,102] unchecked method invocation: method assertDiffType in class VersionDiffCalculatorTest is applied to given types
  required: DiffResult<T,V>,java.lang.Class<D>
  found: DiffResult<VersionDiffCalculatorTest.MockVersion,java.lang.String>,java.lang.Class<NewCurrentVersionDiffResult>
[WARNING] VersionDiffCalculatorTest.java:[34,102] unchecked conversion
  required: NewCurrentVersionDiffResult<VersionDiffCalculatorTest.MockVersion,java.lang.String>
  found:    NewCurrentVersionDiffResult


我希望它能正常工作并且没有警告。

我了解@SuppressWarnings("unchecked"),我在其他地方也正在使用它。但是这种情况显然是坏的,因为当我告诉IDEA从assertDiffType(result, NewCurrentVersionDiffResult.class)声明局部变量时,它会生成

NewCurrentVersionDiffResult newCurrentVersionDiffResult =


并不是

NewCurrentVersionDiffResult<MockVersion, String> newCurrentVersionDiffResult =


同样,警告是关于assertDiffType()方法的调用,而不是方法本身。

最佳答案

您正在将NewCurrentVersionDiffResult.class传递给Class<D>参数的方法,这是它确定D类型的方法,这也是返回类型。注意那里的NewCurrentVersionDiffResult缺少通用参数。这就是为什么该方法返回原始类型的原因。

不幸的是,您不能只执行NewCurrentVersionDiffResult<MockVersion, String>.class。如何处理is answered here的问题;长话短说,您应该使用TypeToken中的Guava library

@SuppressWarnings("unchecked")
private static <D extends DiffResult<T, V>, T extends ProductDataVersion<T>, V> D assertDiffType(final DiffResult<T, V> result, final TypeToken<D> type) {
    Assert.assertThat(result, CoreMatchers.instanceOf(type.getRawType()));
    return (D) result;
}


这样,您可以执行以下操作:

NewCurrentVersionDiffResult<MockVersion, String> newCurrentVersionDiffResult = assertDiffType(result,
        new TypeToken<NewCurrentVersionDiffResult<MockVersion, String>>() {});

10-05 21:52