Example usage for java.lang.reflect Type getTypeName

List of usage examples for java.lang.reflect Type getTypeName

Introduction

In this page you can find the example usage for java.lang.reflect Type getTypeName.

Prototype

default String getTypeName() 

Source Link

Document

Returns a string describing this type, including information about any type parameters.

Usage

From source file:ca.oson.json.util.ObjectUtil.java

public static <E> Class getTypeComponentClass(java.lang.reflect.Type type) {
    Class cl = type.getClass();/*w ww.  jav  a 2s.c  o m*/

    if (ComponentType.class.isAssignableFrom(cl)) {
        ComponentType componentType = (ComponentType) type;
        return componentType.getMainComponentType();
    }

    //java.util.List<ca.oson.json.test.Dataset>
    String className = type.getTypeName();
    Class ctype = getComponentType(className);

    if (ctype != null) {
        return ctype;
    }

    // Collection<String>, return String.class
    if (ParameterizedType.class.isAssignableFrom(cl)) {
        java.lang.reflect.ParameterizedType pt = (java.lang.reflect.ParameterizedType) type;

        if (pt.getActualTypeArguments().length > 0) {
            //return pt.getActualTypeArguments()[0].getClass();
            className = pt.getActualTypeArguments()[0].getTypeName();
            try {
                return Class.forName(className);
            } catch (ClassNotFoundException e) {
                // e.printStackTrace();
            }
        }

        // GenericArrayType represents an array type whose component
        // type is either a parameterized type or a type variable.
    } else if (java.lang.reflect.GenericArrayType.class.isAssignableFrom(cl)) {
        java.lang.reflect.GenericArrayType pt = (java.lang.reflect.GenericArrayType) type;

        return getTypeClass(pt.getGenericComponentType());

    } else if (java.lang.reflect.TypeVariable.class.isAssignableFrom(cl)) {
        java.lang.reflect.TypeVariable pt = (java.lang.reflect.TypeVariable) type;

        java.lang.reflect.Type[] types = pt.getBounds();

        if (types != null && types.length > 0) {
            return getTypeClass(types[0]);
        }
    }

    return null;
}

From source file:ro.cosu.vampires.server.rest.controllers.AbstractControllerTest.java

@SuppressWarnings("unchecked")
private Class<?> getValueClass() throws ClassNotFoundException {
    Type typeValue = ((ParameterizedType) getTypeTokenService().getType()).getActualTypeArguments()[0];
    return Class.forName(typeValue.getTypeName());
}

From source file:org.apache.servicecomb.common.rest.codec.param.BodyProcessorCreator.java

@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
    JavaType targetType = TypeFactory.defaultInstance().constructType(genericParamType);
    boolean rawJson = ClassUtils.isRawJsonType(parameter);
    if (genericParamType.getTypeName().equals(String.class.getTypeName()) && rawJson) {
        return new RawJsonBodyProcessor(targetType, parameter.getRequired());
    }/*from  w  w  w  .  ja v  a2 s .  c  o  m*/

    return new BodyProcessor(targetType, parameter.getRequired());
}

From source file:org.ambraproject.wombat.service.remote.JsonService.java

/**
 * Serialize the content of a stream to an object.
 *
 * @param responseType the object type into which to serialize the JSON code
 * @param reader       the source of the JSON code
 * @param source       an object whose {@code toString()} describes where the JSON code came from (for logging only)
 * @return the deserialized object//from w w  w . j a  v a  2  s . com
 * @throws IOException
 */
private <T> T deserializeStream(Type responseType, Reader reader, Object source) throws IOException {
    T value;
    try {
        value = gson.fromJson(reader, responseType);
    } catch (JsonSyntaxException e) {
        String message = String.format("Could not deserialize %s from stream at: %s. Message: %s",
                responseType.getTypeName(), source, e.getMessage());
        throw new ServiceResponseFormatException(message, e);
    }
    if (value == null) {
        String message = String.format("Could not deserialize %s from null/empty stream at: %s",
                responseType.getTypeName(), source);
        throw new ServiceResponseFormatException(message);
    }
    return value;
}

From source file:org.springframework.cloud.function.web.RequestProcessor.java

private Type getItemType(Object function) {
    Class<?> inputType = this.inspector.getInputType(function);
    if (!Collection.class.isAssignableFrom(inputType)) {
        return inputType;
    }/*w  ww .  j  av a  2  s . co  m*/
    Type type = this.inspector.getRegistration(function).getType().getType();
    if (type instanceof ParameterizedType) {
        type = ((ParameterizedType) type).getActualTypeArguments()[0];
    } else {
        for (Type iface : ((Class<?>) type).getGenericInterfaces()) {
            if (iface.getTypeName().startsWith("java.util.function")) {
                type = ((ParameterizedType) iface).getActualTypeArguments()[0];
                break;
            }
        }
    }
    if (type instanceof ParameterizedType) {
        type = ((ParameterizedType) type).getActualTypeArguments()[0];
    } else {
        type = inputType;
    }
    return type;
}

From source file:org.structr.core.entity.SchemaMethod.java

private String getGenericMethodParameter(final List<Type> types, final Method method) {

    final List<String> typeParameterNames = new LinkedList<>();

    for (final Type type : types) {

        if (type instanceof TypeVariable && ((TypeVariable) type).getGenericDeclaration().equals(method)) {

            // method defines its own generic type
            typeParameterNames.add(type.getTypeName());
        }/*from w  ww  .j a v  a 2 s  .  c  o  m*/
    }

    if (typeParameterNames.isEmpty()) {
        return "";
    }

    return "<" + StringUtils.join(typeParameterNames, ", ") + "> ";
}

From source file:natalia.dymnikova.configuration.ConfigBeanPostProcessor.java

private Object convert(final Type targetType, final Config config, final String path) {
    if (targetType == Config.class) {
        if (path.length() == 0) {
            return config;
        }/*from  w w w . j  ava2s.  c  o  m*/
        return config.getConfig(path);
    } else if (targetType == int.class || targetType == Integer.class) {
        return config.getInt(path);
    } else if (targetType == long.class || targetType == Long.class) {
        return config.getLong(path);
    } else if (targetType == boolean.class || targetType == Boolean.class) {
        return config.getBoolean(path);
    } else if (targetType == String.class) {
        return config.getString(path);
    } else if (targetType == double.class || targetType == Double.class) {
        return config.getDouble(path);
    } else if (targetType == Duration.class) {
        return config.getDuration(path);
    } else if (targetType == ConfigMemorySize.class) {
        return config.getMemorySize(path);
    } else if (targetType == Path.class) {
        return Paths.get(config.getString(path));
    } else if (targetType == List.class) {
        final Type type = ((ParameterizedType) targetType).getActualTypeArguments()[0];
        if (type == String.class) {
            return config.getStringList(path);
        } else if (type == Long.class) {
            return config.getLongList(path);
        } else if (type == Integer.class) {
            return config.getIntList(path);
        } else {
            throw new UnsupportedOperationException("Unsupported type of a List field " + type.getTypeName());
        }
    } else {
        return config.getValue(path).unwrapped();
    }
}

From source file:org.structr.core.entity.SchemaMethod.java

private boolean getSignature(final Class type, final String methodName, final ActionEntry entry) {

    // superclass is AbstractNode
    for (final Method method : type.getMethods()) {

        if (methodName.equals(method.getName()) && (method.getModifiers() & Modifier.STATIC) == 0) {

            final Type[] parameterTypes = method.getGenericParameterTypes();
            final Type returnType = method.getGenericReturnType();
            final List<Type> types = new LinkedList<>();

            // compile list of types to check for generic type parameter
            types.addAll(Arrays.asList(parameterTypes));
            types.add(returnType);/*  ww w .  j av  a  2  s .  c o  m*/

            final String genericTypeParameter = getGenericMethodParameter(types, method);

            // check for generic return type, and if the method defines its own generic type
            if (returnType instanceof TypeVariable
                    && ((TypeVariable) returnType).getGenericDeclaration().equals(method)) {

                // method defines its own generic type
                entry.setReturnType(genericTypeParameter + returnType.getTypeName());

            } else {

                // non-generic return type
                final Class returnClass = method.getReturnType();
                if (returnClass.isArray()) {

                    entry.setReturnType(genericTypeParameter + returnClass.getComponentType().getName() + "[]");

                } else {

                    entry.setReturnType(genericTypeParameter + method.getReturnType().getName());
                }
            }

            for (final Parameter parameter : method.getParameters()) {

                String typeName = parameter.getParameterizedType().getTypeName();
                String name = parameter.getType().getSimpleName();

                if (typeName.contains("$")) {
                    typeName = typeName.replace("$", ".");
                }

                entry.addParameter(typeName, parameter.getName());
            }

            for (final Class exception : method.getExceptionTypes()) {
                entry.addException(exception.getName());
            }

            entry.setOverrides(getProperty(overridesExisting));
            entry.setCallSuper(getProperty(callSuper));

            // success
            return true;
        }
    }

    return false;
}

From source file:com.prepaird.objectgraphdb.ObjectGraphDb.java

private <E> Class<E> getCollectionGenericType(Field f) {
    //since this is an iterable we actually need the generic type of the iterable
    //see http://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list 
    Type type = f.getGenericType();
    if (type instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) type;
        return paramType.getActualTypeArguments().length > 0 ? (Class<E>) paramType.getActualTypeArguments()[0]
                : null;/*from  w w  w .j av a  2 s.  c om*/
    } else if (type instanceof Class) {
        return (Class) type;
    } else {
        Log.error("cannot determine type of " + type.getTypeName());
        return null;
    }
}

From source file:org.evosuite.testcase.fm.MethodDescriptor.java

private String initMatchers(GenericMethod method, GenericClass retvalType) {

    String matchers = "";
    Type[] types = method.getParameterTypes();
    List<GenericClass> parameterClasses = method.getParameterClasses();
    for (int i = 0; i < types.length; i++) {
        if (i > 0) {
            matchers += " , ";
        }//from   ww  w  .  ja v a 2 s  . c  o m

        Type type = types[i];
        GenericClass genericParameter = parameterClasses.get(i);
        if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
            matchers += "anyInt()";
        } else if (type.equals(Long.TYPE) || type.equals(Long.class)) {
            matchers += "anyLong()";
        } else if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
            matchers += "anyBoolean()";
        } else if (type.equals(Double.TYPE) || type.equals(Double.class)) {
            matchers += "anyDouble()";
        } else if (type.equals(Float.TYPE) || type.equals(Float.class)) {
            matchers += "anyFloat()";
        } else if (type.equals(Short.TYPE) || type.equals(Short.class)) {
            matchers += "anyShort()";
        } else if (type.equals(Character.TYPE) || type.equals(Character.class)) {
            matchers += "anyChar()";
        } else if (type.equals(String.class)) {
            matchers += "anyString()";
        } else {
            if (type.getTypeName().equals(Object.class.getName())) {
                /*
                Ideally here we should use retvalType to understand if the target class
                is using generics and if this method parameters would need to be handled
                accordingly. However, doing it does not seem so trivial...
                so a current workaround is that, when a method takes an Object as input (which is
                that would happen in case of Generics T), we use the undetermined "any()"
                 */
                matchers += "any()";
            } else {
                if (type instanceof Class) {
                    matchers += "any(" + ((Class) type).getCanonicalName() + ".class)";
                } else {
                    //what to do here? is it even possible?
                    matchers += "any(" + genericParameter.getRawClass().getCanonicalName() + ".class)";
                    // matchers += "any(" + type.getTypeName() + ".class)";
                }
            }
        }
    }

    return matchers;
}