Fail earlier for some incorrect owner types. (#450)

This commit is contained in:
Eric Cochran
2018-02-24 01:46:42 -08:00
committed by Jesse Wilson
parent ed1ea5a755
commit 8e28dd4ad7
2 changed files with 23 additions and 4 deletions

View File

@@ -503,11 +503,18 @@ 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)) {
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);
this.rawType = canonicalize(rawType);

View File

@@ -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.