Skip to content

Commit

Permalink
Review: Add convenience method for cases where we know this type is a…
Browse files Browse the repository at this point in the history
…n array (or we've already checked javaClass.isArray())

Issue: #187
Signed-off-by: Peter Gafert <peter.gafert@tngtech.com>
  • Loading branch information
codecholeric committed Nov 3, 2019
1 parent b10dde6 commit d63d927
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,25 @@ public boolean isArray() {
return javaType.isArray();
}

/**
* This is a convenience method for {@link #tryGetComponentType()} in cases where
* clients know that this type is certainly an array type and thus the component type present.
* @throws IllegalArgumentException if this class is no array
* @return The result of {@link #tryGetComponentType()}
*/
@PublicAPI(usage = ACCESS)
public JavaClass getComponentType() {
return tryGetComponentType().getOrThrow(new IllegalArgumentException(
String.format("Type %s is no array", getSimpleName())));
}

/**
* Returns the component type of this class, if this class is an array, otherwise
* {@link Optional#absent()}. The component type is the type of the elements of an array type.
* Consider {@code String[]}, then the component type would be {@code String}.
* Likewise for {@code String[][]} the component type would be {@code String[]}.
* @return The component type, if this type is an array, otherwise {@link Optional#absent()}
*/
@PublicAPI(usage = ACCESS)
Optional<JavaClass> tryGetComponentType() {
return componentType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,13 @@ class OnlyReferencingMultiDimArray {
.get(OnlyReferencingMultiDimArray.class);

JavaClass arrayType = javaClass.getField("field").getRawType();
JavaClass twoDim = arrayType.tryGetComponentType().get();
JavaClass twoDim = arrayType.getComponentType();
assertThat(twoDim.getName()).isEqualTo(OnlyReferencingMultiDimArray[][].class.getName());

JavaClass oneDim = twoDim.tryGetComponentType().get();
JavaClass oneDim = twoDim.getComponentType();
assertThat(oneDim.getName()).isEqualTo(OnlyReferencingMultiDimArray[].class.getName());

JavaClass original = oneDim.tryGetComponentType().get();
JavaClass original = oneDim.getComponentType();
assertThat(original).isEqualTo(javaClass);
}

Expand Down

0 comments on commit d63d927

Please sign in to comment.