public final class ObjectUtil extends Object
java.lang.Object
-related utility methods.Modifier and Type | Method and Description |
---|---|
static <T> T |
almostNull()
This method returns
null although it is declared @NotNull . |
static <T> boolean |
equals(T o1,
T o2)
The often-needed "equal" method that handles
null references. |
static <T> T |
fromString(String text,
Class<T> targetType)
Converts a string to an object of the given targetType.
|
static int |
hashCode(Object o) |
static <T> T |
or(T lhs,
T rhs) |
static <T> String |
toString(T value,
String defaultValue) |
public static <T> boolean equals(@Nullable T o1, @Nullable T o2)
null
references.
Redeemed by java.util.Objects.equals(Object, Object)
which is available since Java 1.7.
null
, or are CharSequence
s with equal contents, or are equalpublic static int hashCode(@Nullable Object o)
Null
iff o == null
, otherwise o.hashCode()
public static <T> String toString(@Nullable T value, String defaultValue)
value.toString()
or the defaultValue iff value == null
public static <T> T or(@Nullable T lhs, T rhs)
lhs == null
public static <T> T fromString(String text, Class<T> targetType)
For primitive targetTypes, the corresponding wrapper object is returned.
Supports all primitive types (except void
), their wrapper types, String
, char[]
,
Charset
, Class
, Pattern
, enum types, and classes that have a single-string-parameter
constructor.
Supports (one-dimensional) arrays of these types, where the text is split into words at commas and/or whitespace, and each word converted to the component type.
Does not support collections, including EnumSet
s, because the element type cannot be determined
through REFLECTION. Usage of an array is recommended as a workaround, as follows:
String s = "RED,GREEN";
Color[] tmp = ObjectUtil.fromString(s, Color[].class);
List<Color> list = Arrays.asList(tmp);
EnumSet<Color> enumSet = EnumSet.copyOf(Arrays.asList(tmp));
Set<Color> set = new HashSet<String>(Arrays.asList(tmp));
NumberFormatException
- The string could not be converted to the targetTypeIllegalArgumentException
- The string could not be converted to the targetTypeRuntimeException
- The string could not be converted to the targetTypepublic static <T> T almostNull()
null
although it is declared @NotNull
. This comes in handy to
initialize a field that is declared as NotNull @NotNull
, but is filled reflectively, e.g. by
frameworks like JUNIT or SPRING.Copyright © 2018 Arno Unkrig. All rights reserved.