public final class TypeUtils
extends java.lang.Object
Modifier and Type | Method and Description |
---|---|
static <T,U extends T> |
castStream(java.lang.Class<U> cls)
Filter out members of a subtype from a stream of some base type.
|
static <T> java.util.function.Function<java.lang.Object,java.util.Optional<T>> |
optionalCast(java.lang.Class<T> cls) |
static <T> java.util.Optional<T> |
optionalCast(java.lang.Object value,
java.lang.Class<T> cls)
If 'value' can be cast into 'cls',
returns an Optional of that casted value.
|
static <T> java.util.function.Function<java.util.Optional<T>,java.util.stream.Stream<T>> |
optionalStream()
Turns a Stream of
Optional<T> s into a Stream of the type T wrapped by the optional,
dropping non-present values. |
static <T> T |
tryInstantiate(java.lang.Class<T> type)
Tries to create a new instance of
T using a public no-arg ("default") constructor. |
public static <T> java.util.Optional<T> optionalCast(java.lang.Object value, java.lang.Class<T> cls)
public static <T> java.util.function.Function<java.lang.Object,java.util.Optional<T>> optionalCast(java.lang.Class<T> cls)
public static <T,U extends T> java.util.function.Function<T,java.util.stream.Stream<U>> castStream(java.lang.Class<U> cls)
Filter out members of a subtype from a stream of some base type. For example, this code:
getComponents().stream()
.filter(c -> c instanceof Widget)
.map(c -> (Widget) c)
.forEach(w -> w.setSource(...))
can be turned into:
getComponents()
.flatMap(TypeUtils.castStream(Widget.class))
.forEach(w -> w.setSource(...))
public static <T> java.util.function.Function<java.util.Optional<T>,java.util.stream.Stream<T>> optionalStream()
Optional<T>
s into a Stream of the type T wrapped by the optional,
dropping non-present values.public static <T> T tryInstantiate(java.lang.Class<T> type) throws java.lang.IllegalAccessException, java.lang.InstantiationException
T
using a public no-arg ("default") constructor.T
- the type of the object to be createdtype
- the type to create a new instance ofT
created with a constructor matching the given argumentsjava.lang.IllegalAccessException
- if the constructor matching the given arguments is not publicjava.lang.InstantiationException
- if the class is abstract