Contract { @SuppressWarnings("unchecked") public static <T> T asNotNull(T input, String message) { if (input == null) throw new NullPointerException(message); if (input.getClass().isArray()) { if (!input.getClass().getComponentType().isPrimitive()) { T[] array = (T[]) input; for (int i = 0; i < array.length; i++) { asNotNull(array[i], message); } } } return input; } private  Contract(); @SuppressWarnings("unchecked") static T asNotNull(T input, String message);  }
@Test public void testAsNotNull() { Contract.asNotNull("1", "Works"); Contract.asNotNull(new String[]{}, "Works"); Contract.asNotNull(new String[0], "Works"); Contract.asNotNull(new String[]{"1"}, "Works"); Contract.asNotNull(new String[][]{}, "Works"); Contract.asNotNull(new String[0][0], "Works"); Contract.asNotNull(new String[][]{new String[]{}}, "Works"); Contract.asNotNull(new String[][]{new String[0]}, "Works"); Contract.asNotNull(new String[][]{new String[]{"1"}}, "Works"); try { Contract.asNotNull(null, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } try { Contract.asNotNull(new String[]{null}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } try { Contract.asNotNull(new String[1], "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } try { Contract.asNotNull(new String[]{"1", null}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } try { Contract.asNotNull(new String[]{"1", null, "2"}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } try { Contract.asNotNull(new String[][]{new String[1]}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } Contract.asNotNull(new int[]{}, "Works"); Contract.asNotNull(new int[0], "Works"); Contract.asNotNull(new int[]{1}, "Works"); Contract.asNotNull(new int[1], "Works"); Contract.asNotNull(new int[1][0], "Works"); Contract.asNotNull(new int[1][1], "Works"); int[] badArray = null; try { Contract.asNotNull(badArray, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } int[][] badArray2 = null; try { Contract.asNotNull(badArray2, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { } }