Package blue.endless.jankson.magic
Class TypeMagic
java.lang.Object
blue.endless.jankson.magic.TypeMagic
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic Class<?>classForType(Type t) This is a surprisingly intractable problem in Java: "Type" pretty much represents all possible states of reified and unreified type information, and each kind of Type has different, mutually exclusive, and often unintended ways of uncovering its (un-reified) class.static <U> UcreateAndCast(Class<U> t, boolean failFast) Attempts to create a new instance of the specified class using its no-arg constructor, if it has one.static <U> UAttempts to create a new instance of type t, and (unsafely) cast it to the target type U.static <U> Ustatic <T> TExtremely unsafely casts an object into another type.
-
Constructor Details
-
TypeMagic
public TypeMagic()
-
-
Method Details
-
classForType
This is a surprisingly intractable problem in Java: "Type" pretty much represents all possible states of reified and unreified type information, and each kind of Type has different, mutually exclusive, and often unintended ways of uncovering its (un-reified) class.Generally it's much safer to use this for the type from a *field* than a blind type from an argument.
-
createAndCast
Attempts to create a new instance of type t, and (unsafely) cast it to the target type U. This might work even if the class is private or has a private constructor.- Type Parameters:
U- the target type.- Parameters:
t- the source type. The object will be created as this type.- Returns:
- an object of type t, cast to type U. If any part of this process fails, this method silently returns null instead.
-
createAndCastCarefully
- Throws:
DeserializationException
-
createAndCast
@Nullable public static <U> U createAndCast(Class<U> t, boolean failFast) throws DeserializationException Attempts to create a new instance of the specified class using its no-arg constructor, if it has one. This might work even if the class is private or the constructor is private/hidden!- Type Parameters:
U- the target type.- Parameters:
t- the source type. The object will be created as this type.- Returns:
- a new object of type U. If any part of this process fails, this method silently returns null instead.
- Throws:
DeserializationException
-
shoehorn
Extremely unsafely casts an object into another type. It's possible to mangle a List<Integer> into a List<String> this way, and the JVM might not throw an error until the program attempts to insert a String! So use this method with extreme caution as a last resort.- Type Parameters:
T- the destination type- Parameters:
o- the source object, of any type- Returns:
- the source object cast to T.
-