Class SafeFieldHandle<T,U>
- java.lang.Object
-
- science.aist.jack.reflection.SafeFieldHandle<T,U>
-
public class SafeFieldHandle<T,U> extends Object
SafeFieldHandle
Allows typesafe access to
Field
s. The value is wrapped intoOptional
to allow functional error handling, if theField
is either of the wrong type, or not initialized.This handle also checks initialisation of the
Field
by comparing the value with the datatype default value. The value is either derived from the datatype, or explicitly passed for application specific use cases.- Since:
- 2.3.0
- Author:
- Rainer Meindl
-
-
Constructor Summary
Constructors Constructor Description SafeFieldHandle(Class<T> clazz, String name)
Creates a new instance ofSafeFieldHandle
, where the defaultValue is derived from the type, if possible.SafeFieldHandle(Class<T> clazz, String name, U defaultValue)
Creates a new instance ofSafeFieldHandle
.SafeFieldHandle(Field field)
SafeFieldHandle(Field field, U defaultValue)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description Optional<U>
get(T object)
protected U
getDefaultValue()
Returns the default value for the given type U.protected Optional<U>
tryCast(Object fieldValue)
Tries to cast the fieldValue into the designated type U.
-
-
-
Constructor Detail
-
SafeFieldHandle
public SafeFieldHandle(Field field)
-
SafeFieldHandle
public SafeFieldHandle(Class<T> clazz, String name)
Creates a new instance of
SafeFieldHandle
, where the defaultValue is derived from the type, if possible. Might fail, if noField
witht he provided name is found.
-
-
Method Detail
-
get
public Optional<U> get(T object)
Accesses the unsafe
Field
and wraps it in anOptional
of the type this class thinks it is. If either the access, or the conversion of the value fails, as well as if theField
s value is equal to the defaultValue defined by this handle- Parameters:
object
- The instance, whose fields needs to be accessed safely.- Returns:
- Optional, either containing the typesafe value of the field or Optional.empty() s
-
tryCast
protected Optional<U> tryCast(Object fieldValue)
Tries to cast the fieldValue into the designated type U. If the cast fails, or the value is null, an empty
Optional
is returned.- Parameters:
fieldValue
- an extracted value of the unsafeField, which should be casted into a type of U- Returns:
- an
Optional
of U, either holding the mapped value of fieldValue, or empty, if the cast fails.
-
getDefaultValue
protected U getDefaultValue()
Returns the default value for the given type U.
- Returns:
- the default value for the given type U.
-
-