Example usage for java.lang.reflect Type toString

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.openflexo.antar.binding.TypeUtils.java

public static String simpleRepresentation(Type aType) {
    if (aType == null) {
        return "null";
    }/*from  w  ww. j  a va  2s. c  om*/
    if (aType instanceof CustomType) {
        return ((CustomType) aType).simpleRepresentation();
    }
    if (aType instanceof Class) {
        return ((Class) aType).getSimpleName();
    } else if (aType instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) aType;
        StringBuilder sb = new StringBuilder();
        sb.append(simpleRepresentation(t.getRawType())).append("<");
        boolean isFirst = true;
        for (Type st : t.getActualTypeArguments()) {
            sb.append(isFirst ? "" : ",").append(simpleRepresentation(st));
            isFirst = false;
        }
        sb.append(">");
        return sb.toString();
    }
    return aType.toString();
}

From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

public <T> Class<T> inferValueClassForListOrSet(Type genericType, Class<?> entityClass) {
    log.debug("Infer parameterized value class for collection type {} of entity class {} ",
            genericType.toString(), entityClass.getCanonicalName());

    Class<T> valueClass;/*from   ww w  .  ja  va  2 s. c om*/
    if (genericType instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) genericType;
        Type[] actualTypeArguments = pt.getActualTypeArguments();
        if (actualTypeArguments.length > 0) {
            Type type = actualTypeArguments[actualTypeArguments.length - 1];
            valueClass = getClassFromType(type);
        } else {
            throw new AchillesBeanMappingException("The type '" + genericType.getClass().getCanonicalName()
                    + "' of the entity '" + entityClass.getCanonicalName() + "' should be parameterized");
        }
    } else {
        throw new AchillesBeanMappingException("The type '" + genericType.getClass().getCanonicalName()
                + "' of the entity '" + entityClass.getCanonicalName() + "' should be parameterized");
    }

    log.trace("Inferred value class : {}", valueClass.getCanonicalName());

    return valueClass;
}

From source file:com.sm.query.utils.QueryUtils.java

public static Object convert(Type type, Result result) {
    if (isSameType(type, result.getType()))
        return result.getValue();
    switch (type) {
    case INT:/*from   ww  w  .  j av a2s.  c  om*/
    case INTS:
        return Integer.valueOf((String) result.getValue());
    case SHORT:
    case SHORTS:
        return Short.valueOf((String) result.getValue());
    case LONG:
    case LONGS:
        return Long.valueOf((String) result.getValue());
    case FLOAT:
    case FLOATS:
        return Float.valueOf((String) result.getValue());
    case DOUBLE:
    case DOUBLES:
        return Double.valueOf((String) result.getValue());
    case BOOLEAN:
    case BOOLEANS:
        return Boolean.valueOf((String) result.getValue());
    default:
        throw new QueryException(type.toString() + " is not supported yet");
    }
}

From source file:org.openflexo.antar.binding.TypeUtils.java

public static String fullQualifiedRepresentation(Type aType) {
    if (aType == null) {
        return null;
    }//from w ww .j  a  va  2s .  com
    if (aType instanceof CustomType) {
        return ((CustomType) aType).fullQualifiedRepresentation();
    }
    if (aType instanceof Class) {
        return ((Class) aType).getName();
    } else if (aType instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) aType;
        StringBuilder sb = new StringBuilder();
        sb.append(fullQualifiedRepresentation(t.getRawType())).append("<");
        boolean isFirst = true;
        for (Type st : t.getActualTypeArguments()) {
            sb.append(isFirst ? "" : ",").append(fullQualifiedRepresentation(st));
            isFirst = false;
        }
        sb.append(">");
        return sb.toString();
    }
    return aType.toString();
}

From source file:org.openmrs.module.sync.SyncUtil.java

public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) {
    Object o = null;/*from w ww.j a  va  2  s .  c  om*/

    // the String value on the node specifying the "type"
    String nodeDefinedClassName = null;
    if (n != null) {
        Node tmpNode = n.getAttributes().getNamedItem("type");
        if (tmpNode != null)
            nodeDefinedClassName = tmpNode.getTextContent();
    }

    // TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ? 
    // TODO: Speed up sync by returning after "o" is first set?  Or are we doing "last field wins" ?
    for (Field f : allFields) {
        //log.debug("field is " + f.getName());
        if (f.getName().equals(fieldName)) {
            Class classType = null;
            String className = f.getGenericType().toString(); // the string class name for the actual field

            // if its a collection, set, list, etc
            if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) {
                ParameterizedType pType = (ParameterizedType) f.getGenericType();
                classType = (Class) pType.getRawType(); // can this be anything but Class at this point?!
            }

            if (className.startsWith("class ")) {
                className = className.substring("class ".length());
                classType = (Class) f.getGenericType();
            } else {
                log.trace("Abnormal className for " + f.getGenericType());
            }

            if (classType == null) {
                if ("int".equals(className)) {
                    return new Integer(fieldVal);
                } else if ("long".equals(className)) {
                    return new Long(fieldVal);
                } else if ("double".equals(className)) {
                    return new Double(fieldVal);
                } else if ("float".equals(className)) {
                    return new Float(fieldVal);
                } else if ("boolean".equals(className)) {
                    return new Boolean(fieldVal);
                } else if ("byte".equals(className)) {
                    return new Byte(fieldVal);
                } else if ("short".equals(className)) {
                    return new Short(fieldVal);
                }
            }

            // we have to explicitly create a new value object here because all we have is a string - won't know how to convert
            if (OpenmrsObject.class.isAssignableFrom(classType)) {
                o = getOpenmrsObj(className, fieldVal);
            } else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName)
                    || "java.lang.Integer".equals(nodeDefinedClassName))) {
                // if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from
                // an integer to a uuid by the HibernateSyncInterceptor.  The nodeDefinedClassName is the node.type which is the 
                // actual classname as defined by the PersonAttributeType.format.  However, the field.getClassName is 
                // still an integer because thats what the db stores.  we need to convert the uuid to the pk integer and return it
                OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
                o = obj.getId();
            } else if ("java.lang.String".equals(className) && !("text".equals(nodeDefinedClassName)
                    || "string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName)
                    || "integer".equals(nodeDefinedClassName)
                    || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) {
                // if we're dealing with a field like PersonAttribute.value, the actual value was changed from
                // a string to a uuid by the HibernateSyncInterceptor.  The nodeDefinedClassName is the node.type which is the 
                // actual classname as defined by the PersonAttributeType.format.  However, the field.getClassName is 
                // still String because thats what the db stores.  we need to convert the uuid to the pk integer/string and return it
                OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
                if (obj == null) {
                    if (StringUtils.hasText(fieldVal)) {
                        // If we make it here, and we are dealing with person attribute values, then just return the string value as-is
                        if (PersonAttribute.class.isAssignableFrom(f.getDeclaringClass())
                                && "value".equals(f.getName())) {
                            o = fieldVal;
                        } else {
                            // throw a warning if we're having trouble converting what should be a valid value
                            log.error("Unable to convert value '" + fieldVal + "' into a "
                                    + nodeDefinedClassName);
                            throw new SyncException("Unable to convert value '" + fieldVal + "' into a "
                                    + nodeDefinedClassName);
                        }
                    } else {
                        // if fieldVal is empty, just save an empty string here too
                        o = "";
                    }
                } else {
                    o = obj.getId().toString(); // call toString so the class types match when looking up the setter
                }
            } else if (Collection.class.isAssignableFrom(classType)) {
                // this is a collection of items. this is intentionally not in the convertStringToObject method

                Collection tmpCollection = null;
                if (Set.class.isAssignableFrom(classType))
                    tmpCollection = new LinkedHashSet();
                else
                    tmpCollection = new Vector();

                // get the type of class held in the collection
                String collectionTypeClassName = null;
                java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType) f
                        .getGenericType()).getActualTypeArguments()[0];
                if (collectionType.toString().startsWith("class "))
                    collectionTypeClassName = collectionType.toString().substring("class ".length());

                // get the type of class defined in the text node
                // if it is different, we could be dealing with something like Cohort.memberIds
                // node type comes through as java.util.Set<classname>
                String nodeDefinedCollectionType = null;
                int indexOfLT = nodeDefinedClassName.indexOf("<");
                if (indexOfLT > 0)
                    nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT + 1,
                            nodeDefinedClassName.length() - 1);

                // change the string to just a comma delimited list
                fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", "");

                for (String eachFieldVal : fieldVal.split(",")) {
                    eachFieldVal = eachFieldVal.trim(); // take out whitespace
                    if (!StringUtils.hasText(eachFieldVal))
                        continue;
                    // try to convert to a simple object
                    Object tmpObject = convertStringToObject(eachFieldVal, (Class) collectionType);

                    // convert to an openmrs object
                    if (tmpObject == null && nodeDefinedCollectionType != null)
                        tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId();

                    if (tmpObject == null)
                        log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName);
                    else
                        tmpCollection.add(tmpObject);
                }

                o = tmpCollection;
            } else if (Map.class.isAssignableFrom(classType) || Properties.class.isAssignableFrom(classType)) {
                Object tmpMap = SyncUtil.getNormalizer(classType).fromString(classType, fieldVal);

                //if we were able to convert and got anything at all back, assign it
                if (tmpMap != null) {
                    o = tmpMap;
                }
            } else if ((o = convertStringToObject(fieldVal, classType)) != null) {
                log.trace("Converted " + fieldVal + " into " + classType.getName());
            } else {
                log.debug("Don't know how to deserialize class: " + className);
            }
        }
    }

    if (o == null)
        log.debug("Never found a property named: " + fieldName + " for this class");

    return o;
}

From source file:com.agimatec.validation.jsr303.Jsr303MetaBeanFactory.java

private String stringForType(Type clazz) {
    if (clazz instanceof Class) {
        if (((Class) clazz).isArray()) {
            return ((Class) clazz).getComponentType().getName() + "[]";
        } else {//from   w ww . j  a  v  a2s .  co m
            return ((Class) clazz).getName();
        }
    } else {
        return clazz.toString();
    }
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

@Override
public Object generate(Type type, ITestParamState initParam, Map<String, Type> itestGenericMap,
        ITestContext iTestContext) {//from ww  w . j a  va2s.  c o  m
    try {
        return generateRandom(type, itestGenericMap, iTestContext);
    } catch (ITestException e) {
        e.addPrefix(type.toString());
        throw e;
    }
}

From source file:com.redhat.rhn.frontend.xmlrpc.api.ApiHandler.java

private String getType(Type classType, boolean firstParam) {
    if (classType.equals(String.class)) {
        return "string";
    } else if ((classType.equals(Integer.class)) || (classType.equals(int.class))) {
        return "int";
    } else if (classType.equals(Date.class)) {
        return "date";
    } else if (classType.equals(Boolean.class) || classType.equals(boolean.class)) {
        return "boolean";
    } else if (classType.equals(Map.class)) {
        return "struct";
    } else if ((classType.equals(List.class)) || (classType.equals(Set.class))
            || (classType.toString().contains("class [L")) || (classType.toString().contains("class [I"))) {
        return "array";
    } else if (classType.toString().contains("class [B")) {
        return "base64";
    } else if (classType.equals(com.redhat.rhn.domain.user.User.class) && firstParam) {
        // this is a workaround needed due to ef911709..2765f023bd
        return "string";
    } else {//from  w  ww .  j  a  v  a  2s  . c  om
        return "struct";
    }
}

From source file:org.janusgraph.core.attribute.Geoshape.java

@Override
public String toString() {
    Type type = getType();
    StringBuilder s = new StringBuilder();
    s.append(type.toString().toLowerCase());
    switch (type) {
    case POINT:/*w w  w.  j  a  va  2s.  c  om*/
        s.append(getPoint().toString());
        break;
    case CIRCLE:
        s.append(getPoint().toString()).append(":").append(getRadius());
        break;
    default:
        s.append("[");
        for (int i = 0; i < size(); i++) {
            if (i > 0)
                s.append(",");
            s.append(getPoint(i));
        }
        s.append("]");
    }
    return s.toString();
}

From source file:org.ut.biolab.medsavant.MedSavantServlet.java

public String json_invoke(String adapter, String method, String jsonStr) throws IllegalArgumentException {

    adapter = adapter + "Adapter";

    Field selectedAdapter = null;
    for (Field f : MedSavantServlet.class.getDeclaredFields()) {
        if (f.getType().getSimpleName().equalsIgnoreCase(adapter)) {
            selectedAdapter = f;//from  w ww.jav a 2  s .  c  om
        }
    }

    if (selectedAdapter == null) {
        throw new IllegalArgumentException("The adapter " + adapter + " does not exist");
    }

    JsonParser parser = new JsonParser();
    JsonArray gArray = parser.parse(jsonStr).getAsJsonArray();
    JsonElement jse = parser.parse(jsonStr);
    JsonArray jsonArray;

    if (jse.isJsonArray()) {
        jsonArray = jse.getAsJsonArray();
    } else {
        throw new IllegalArgumentException("The json method arguments are not an array");
    }

    Method selectedMethod = null;

    for (Method m : selectedAdapter.getType().getMethods()) {
        if (m.getName().equalsIgnoreCase(method)
                && m.getGenericParameterTypes().length == (jsonArray.size() + 1)) {
            selectedMethod = m;
        }
    }

    if (selectedMethod == null) {
        throw new IllegalArgumentException("The method " + method + " in adapter " + adapter + " with "
                + jsonArray.size() + " arguments does not exist");
    }

    int i = 0;
    Object[] methodArgs = new Object[selectedMethod.getParameterTypes().length];

    try {
        for (Type t : selectedMethod.getGenericParameterTypes()) {
            LOG.debug("Field " + i + " is " + t.toString() + " for method " + selectedMethod.toString());
            methodArgs[i] = (i > 0) ? gson.fromJson(gArray.get(i - 1), t) : session.getSessionId();
            ++i;
        }
    } catch (JsonParseException je) {
        LOG.error(je);
    }

    Object selectedAdapterInstance = null;
    try {
        selectedAdapterInstance = selectedAdapter.get(this);
        if (selectedAdapterInstance == null) {
            throw new NullPointerException(
                    "Requested adapter " + selectedAdapter.getName() + " was not initialized.");
        }
        MethodInvocation methodInvocation = new MethodInvocation(session, gson, selectedAdapterInstance,
                selectedMethod, methodArgs);

        return methodInvocation.invoke();
    } catch (IllegalAccessException iae) {
        throw new IllegalArgumentException("Couldn't execute method with given arguments: " + iae.getMessage());
    } catch (LockException lex) {
        //this shouldn't happen, as locking exceptions can only be thrown by queued method invocations, which
        //are intercepted in the BlockingQueueManager.
        String msg = "Unexpected locking exception thrown in unqueued method invocation.";
        LOG.error(msg);
        throw new IllegalArgumentException(msg + ": " + lex.getMessage());
    }

}