Class Objects, being the first class of sweetener project, provides set of methods to facilitate work with Object known from core of Java language. Among the most popular methods are: deep copy, comparison two object (possible also null object) and null-safe methods.
The public static <T> T deepCopy(T o) method allows user to perform deep copy. A deep copy means that all objects are created again and thanks to this, two objects do not share the same object by copied reference.
Example POJO classes
Well-known issue is comparing two object while the first of them is null. It always ends with NullPointerException. From now to compare two objects, you can use the following methods:
The first one allows to compare two object, where one of them or even two may be null. In case when both objects are null, equals return true, but when only one of them is null, equals always returns false. In other cases the equals method is invoked on the object passed as the first parameter.
The second type of the equals method allows to compare nested objects. The equals method with four parameters is very similar to second one, but the path to the first and second object may be different.
Suppose that in the code there are two Person objects:
Probably not once you seen code like this:
This code has one big defect: is very sensitive to null Object. If for example firstPerson.getCompany() returns null, you will receive NullPointerException.
To avoid such unpleasant surprises you should use:
This method never throws NullPointerException, even in the case when address from above example is null. You can compare two objects with different paths as well.
Return default value of given type when value is null.
We want to avoid such an ugly code:
The solution to this situation is to use:
Custom nullable object
When your nullable object is not listed above you can use OnNullStrategy to create custom behavior. Take a look at the following code:
When hero object is not null - it will remain the same, when it’s null - it will be created and initialized.