【发布时间】:2017-08-08 17:08:54
【问题描述】:
我有一个复杂的方法,它返回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() 方法的调用,而不是针对方法本身。
【问题讨论】: