Objects Example

In Java 7, a new class java.util.Objects was introduced that contains static utility methods for working with objects. It contains methods for dealing with null, computing hashcode, comparing two objects and returning the string representation of an object.

Check if null

@Test
public void objects_isNull () {
    
    boolean isNull = Objects.isNull(null);
    
    assertTrue(isNull);
}

Is non null

@Test
public void objects_nonNull () {
    
    boolean nonNull = Objects.nonNull("");

    assertTrue(nonNull);
}

Require non null

@Test(expected = NullPointerException.class)
public void objects_requireNonNull () {
    
    Integer val = null;
    
    Objects.requireNonNull(val); //throws null pointer
}

Require non null w/ message

@Test
public void objects_requireNonNullMessage () {
    
    Integer val = null;

    try {
        Objects.requireNonNull(val, "Val must not be null");   
    } catch (NullPointerException e) {
        assertEquals("Val must not be null", e.getMessage());
    }
}

Require non null w/ message supplier

@Test
public void objects_requireNonNullMessageSupplier () {
    
    Integer val = null;

    Supplier<String> messageSupplier = new Supplier<String>() {
        @Override
        public String get() {
            return "Val must not be null";
        }
    };
    
    try {
        Objects.requireNonNull(val, messageSupplier);  
    } catch (NullPointerException e) {
        assertEquals("Val must not be null", e.getMessage());
    }
}

Generate hashcode

@Test
public void objects_hashcode () {
    
    int hashCode = Objects.hashCode(this);
    
    assertEquals(1067938912, hashCode);
}