mirror of
https://github.com/fankes/moshi.git
synced 2025-10-19 16:09:21 +08:00
Fail earlier for some incorrect owner types. (#450)
This commit is contained in:
committed by
Jesse Wilson
parent
ed1ea5a755
commit
8e28dd4ad7
@@ -503,10 +503,17 @@ public final class Types {
|
||||
|
||||
ParameterizedTypeImpl(@Nullable Type ownerType, Type rawType, Type... typeArguments) {
|
||||
// Require an owner type if the raw type needs it.
|
||||
if (rawType instanceof Class<?>
|
||||
&& (ownerType == null) != (((Class<?>) rawType).getEnclosingClass() == null)) {
|
||||
throw new IllegalArgumentException(
|
||||
"unexpected owner type for " + rawType + ": " + ownerType);
|
||||
if (rawType instanceof Class<?>) {
|
||||
Class<?> enclosingClass = ((Class<?>) rawType).getEnclosingClass();
|
||||
if (ownerType != null) {
|
||||
if (enclosingClass == null || Types.getRawType(ownerType) != enclosingClass) {
|
||||
throw new IllegalArgumentException(
|
||||
"unexpected owner type for " + rawType + ": " + ownerType);
|
||||
}
|
||||
} else if (enclosingClass != null) {
|
||||
throw new IllegalArgumentException(
|
||||
"unexpected owner type for " + rawType + ": null");
|
||||
}
|
||||
}
|
||||
|
||||
this.ownerType = ownerType == null ? null : canonicalize(ownerType);
|
||||
|
@@ -100,6 +100,15 @@ public final class TypesTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void parameterizedTypeWithIncorrectOwnerProvided() throws Exception {
|
||||
try {
|
||||
Types.newParameterizedTypeWithOwner(A.class, D.class, B.class);
|
||||
fail();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertThat(expected).hasMessage("unexpected owner type for " + D.class + ": " + A.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void arrayOf() {
|
||||
assertThat(Types.getRawType(Types.arrayOf(int.class))).isEqualTo(int[].class);
|
||||
assertThat(Types.getRawType(Types.arrayOf(List.class))).isEqualTo(List[].class);
|
||||
@@ -153,6 +162,9 @@ public final class TypesTest {
|
||||
private static final class C {
|
||||
}
|
||||
|
||||
private static final class D<T> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a parameterized type {@code A<B, C>}, returns B. If the specified type is not a generic
|
||||
* type, returns null.
|
||||
|
Reference in New Issue
Block a user