TypeLiteral¶
- public abstract class org.apache.commons.lang3.reflect.TypeLiteral<T> implements Typed<T>[source]¶
Type literal comparable to
javax.enterprise.util.TypeLiteral, made generally available outside the JEE context. Allows the passing around of a “token” that represents a type in a typesafe manner, as opposed to passing the (non-parameterized)Typeobject itself. Consider:You might see such a typesafe API as:
class Typesafe { <T> T obtain(Class<T> type, ...); }
Consumed in the manner of:
Foo foo = typesafe.obtain(Foo.class, ...);
Yet, you run into problems when you want to do this with a parameterized type:
List<String> listOfString = typesafe.obtain(List.class, ...); // could only give us a raw List
java.lang.reflect.Typemight provide some value:Type listOfStringType = ...; // firstly, how to obtain this? Doable, but not straightforward. List<String> listOfString = (List<String>) typesafe.obtain(listOfStringType, ...); // nongeneric Type would necessitate a cast
The “type literal” concept was introduced to provide an alternative, i.e.:
class Typesafe { <T> T obtain(TypeLiteral<T> type, ...); }
Consuming code looks like:
List<String> listOfString = typesafe.obtain(new TypeLiteral<List<String>>() {}, ...);
This has the effect of “jumping up” a level to tie a
java.lang.reflect.Typeto a type variable while simultaneously making it short work to obtain aTypeinstance for any given type, inline.Additionally
TypeLiteralimplements theTypedinterface which is a generalization of this concept, and which may be implemented in custom classes. It is suggested that APIs be defined in terms of the interface, in the following manner:<T> T obtain(Typed<T> typed, ...);
- Parameters:
<T> – The type
- Since:
3.2
Constructors¶
Constructs a new instance. |
Fields and constants¶
Represented type. |
Methods¶
Gets the |
|