CodeBlocks { @Nonnull public static CodeBlock createUnmodifiableStatement(@Nonnull TypeMirror type, @Nonnull String variable) { if (type.getKind() == TypeKind.ARRAY) { return CodeBlock.of("$T.copyOf($N, $N.length)", Arrays.class, variable, variable); } if (MoreTypes.isTypeOf(List.class, type)) { return CodeBlock.of("new $T<>($N)", ArrayList.class, variable); } if (MoreTypes.isTypeOf(Set.class, type)) { return CodeBlock.of("new $T<>($N)", HashSet.class, variable); } if (MoreTypes.isTypeOf(Map.class, type)) { return CodeBlock.of("new $T<>($N)", HashMap.class, variable); } return CodeBlock.of("$N", variable); } private  CodeBlocks(); @Nonnull static CodeBlock createUnmodifiableStatement(@Nonnull TypeMirror type, @Nonnull String variable);  }
@Test public void createUnmodifiableStatementShouldCopyArrayDefensively() throws Exception { final TypeMirror mirror = mock(TypeMirror.class); when(mirror.getKind()).thenReturn(TypeKind.ARRAY); final CodeBlock actual = CodeBlocks.createUnmodifiableStatement(mirror, "value"); assertThat(actual.toString()) .isEqualTo("java.util.Arrays.copyOf(value, value.length)"); }
@Test public void createUnmodifiableStatementShouldCopyListDefensively() throws Exception { final TypeElement element = elements.getTypeElement(List.class.getCanonicalName()); final TypeMirror mirror = element.asType(); final CodeBlock actual = CodeBlocks.createUnmodifiableStatement(mirror, "value"); assertThat(actual.toString()) .isEqualTo("new java.util.ArrayList<>(value)"); }
@Test public void createUnmodifiableStatementShouldCopySetDefensively() throws Exception { final TypeElement element = elements.getTypeElement(Set.class.getCanonicalName()); final TypeMirror mirror = element.asType(); final CodeBlock actual = CodeBlocks.createUnmodifiableStatement(mirror, "value"); assertThat(actual.toString()) .isEqualTo("new java.util.HashSet<>(value)"); }
@Test public void createUnmodifiableStatementShouldCopyMapDefensively() throws Exception { final TypeElement element = elements.getTypeElement(Map.class.getCanonicalName()); final TypeMirror mirror = element.asType(); final CodeBlock actual = CodeBlocks.createUnmodifiableStatement(mirror, "value"); assertThat(actual.toString()) .isEqualTo("new java.util.HashMap<>(value)"); }
@Test public void createUnmodifiableStatementShouldReturnValue() throws Exception { final TypeElement element = elements.getTypeElement(String.class.getCanonicalName()); final TypeMirror mirror = element.asType(); final CodeBlock actual = CodeBlocks.createUnmodifiableStatement(mirror, "value"); assertThat(actual.toString()) .isEqualTo("value"); }