Search in sources :

Example 1 with GenericArrayTypeImpl

use of sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl in project Gaffer by gchq.

the class JsonSerialisationUtil method getFieldTypeString.

/**
 * Get the string representation of a type of a field within a class.
 *
 * @param clazz   the class containing the field. This is used to try to resolve any generic class arguments
 * @param typeArg the type of the field.
 * @return the type of the field represented as a string.
 */
public static String getFieldTypeString(final Class<?> clazz, final Type typeArg) {
    String typeName = null;
    final boolean isArray = typeArg instanceof GenericArrayTypeImpl;
    Type type = typeArg;
    if (isArray) {
        type = ((GenericArrayTypeImpl) typeArg).getGenericComponentType();
    }
    if (type instanceof TypeVariable) {
        final TypeVariable tv = (TypeVariable) type;
        final GenericDeclaration genericDeclaration = tv.getGenericDeclaration();
        if (null != clazz && genericDeclaration instanceof Class) {
            final Map<TypeVariable<?>, Type> typeArgs = TypeUtils.getTypeArguments(clazz, (Class) genericDeclaration);
            if (null != typeArgs) {
                final Type propType = typeArgs.get(tv);
                if (null != propType) {
                    typeName = propType.getTypeName();
                }
            }
        }
        if (null == typeName) {
            if (null != tv.getBounds() && 1 == tv.getBounds().length) {
                typeName = tv.getBounds()[0].getTypeName();
            } else {
                typeName = type.getTypeName();
            }
        }
    } else {
        typeName = type.getTypeName();
    }
    if (null != typeName) {
        if (isArray) {
            typeName = typeName + "[]";
        }
        // Try and replace any primitive types with the full class name, e.g int/boolean with java.lang.Integer/java.lang.Boolean
        if (!typeName.contains(".")) {
            typeName = SimpleClassNameIdResolver.getClassName(typeName);
        }
        typeName = typeName.replaceAll("\\? extends ", "").replaceAll("\\? super ", "").replaceAll(" ", "");
    }
    return typeName;
}
Also used : Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) TypeVariable(java.lang.reflect.TypeVariable) GenericArrayTypeImpl(sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl) GenericDeclaration(java.lang.reflect.GenericDeclaration)

Aggregations

JavaType (com.fasterxml.jackson.databind.JavaType)1 GenericDeclaration (java.lang.reflect.GenericDeclaration)1 Type (java.lang.reflect.Type)1 TypeVariable (java.lang.reflect.TypeVariable)1 GenericArrayTypeImpl (sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl)1