Example usage for java.lang.reflect Type getClass

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java

/**
 * Return ComponentType, might need to look at the GenericType
 * @param pd ParameterDesc or null if return
 * @param operationDesc OperationDescription
 * @param msrd MarshalServiceRuntimeDescription
 * @return/*from  ww w. j av a2  s  .  c  o  m*/
 */
private static Class getComponentType(ParameterDescription pd, OperationDescription operationDesc,
        MarshalServiceRuntimeDescription msrd) {
    Class componentType = null;
    if (log.isDebugEnabled()) {
        log.debug("start getComponentType");
        log.debug(" ParameterDescription=" + pd);
    }

    // Determine if array, list, or other
    Class cls = null;
    if (pd == null) {
        cls = operationDesc.getResultActualType();
    } else {
        cls = pd.getParameterActualType();
    }

    if (cls != null) {
        if (cls.isArray()) {
            componentType = cls.getComponentType();
        } else if (List.class.isAssignableFrom(cls)) {
            if (log.isDebugEnabled()) {
                log.debug("Parameter is a List: " + cls);
            }
            Method method = msrd.getMethod(operationDesc);
            if (log.isDebugEnabled()) {
                log.debug("Method is: " + method);
            }
            Type genericType = null;
            if (pd == null) {
                genericType = method.getGenericReturnType();
            } else {
                ParameterDescription[] pds = operationDesc.getParameterDescriptions();
                for (int i = 0; i < pds.length; i++) {
                    if (pds[i] == pd) {
                        genericType = method.getGenericParameterTypes()[i];
                    }
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("genericType is: " + genericType.getClass() + " " + genericType);
            }
            if (genericType instanceof Class) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof Class");
                }
                componentType = String.class;
            } else if (genericType instanceof ParameterizedType) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof ParameterizedType");
                }
                ParameterizedType pt = (ParameterizedType) genericType;
                if (pt.getRawType() == Holder.class) {
                    if (log.isDebugEnabled()) {
                        log.debug(" strip off holder");
                    }
                    genericType = pt.getActualTypeArguments()[0];
                    if (genericType instanceof Class) {
                        componentType = String.class;
                    } else if (genericType instanceof ParameterizedType) {
                        pt = (ParameterizedType) genericType;
                    }
                }
                if (componentType == null) {
                    Type comp = pt.getActualTypeArguments()[0];
                    if (log.isDebugEnabled()) {
                        log.debug(" comp =" + comp.getClass() + " " + comp);
                    }
                    if (comp instanceof Class) {
                        componentType = (Class) comp;
                    } else if (comp instanceof ParameterizedType) {
                        componentType = (Class) ((ParameterizedType) comp).getRawType();
                    }
                }
            }

        }
    }

    if (log.isDebugEnabled()) {
        log.debug("end getComponentType=" + componentType);
    }
    return componentType;
}

From source file:org.openehealth.ipf.gazelle.validation.core.GazelleProfileRule.java

protected List<ValidationException> testField(Type type, SegmentType.Field profile, boolean escape) {
    List<ValidationException> exList = new ArrayList<>();

    UsageInfo usage = new UsageInfo(profile);

    // account for MSH 1 & 2 which aren't escaped
    String encoded = null;/*from   w w w. j a v a2  s  .c om*/
    if (!escape && Primitive.class.isAssignableFrom(type.getClass()))
        encoded = ((Primitive) type).getValue();

    exList.addAll(testType(type, profile.getDatatype(), usage, encoded, false));

    // test children
    if (validateChildren) {
        if (profile.getComponents().size() > 0 && !usage.disallowed()) {
            if (Composite.class.isAssignableFrom(type.getClass())) {
                Composite comp = (Composite) type;
                int i = 1;
                boolean nullContext = false;
                for (SegmentType.Field.Component component : profile.getComponents()) {
                    try {
                        SegmentType.Field.Component component2;
                        if (nullContext) {
                            component2 = new SegmentType.Field.Component();
                            try {
                                BeanUtils.copyProperties(component2, component);
                            } catch (InvocationTargetException | IllegalAccessException e) {
                                // nop
                            }
                            component2.setUsage("NULL");
                        } else {
                            component2 = component;
                            if ((i == 1) && profile.isNullable()
                                    && PipeParser.encode(comp.getComponent(0), this.enc).equals("\"\"")) {
                                nullContext = true;
                            }
                        }

                        exList.addAll(testComponent(comp.getComponent(i - 1), component2));
                    } catch (DataTypeException de) {
                        profileNotHL7Compliant(exList, COMPONENT_TYPE_MISMATCH, type.getName(), i);
                    }
                    ++i;
                }
                exList.addAll(checkUndefinedComponents(comp, profile.getComponents().size()));
            } else {
                profileNotHL7Compliant(exList, WRONG_FIELD_TYPE, type.getClass().getName());
            }
        }
    }
    return exList;
}

From source file:org.openehealth.ipf.gazelle.validation.core.GazelleProfileRule.java

protected List<ValidationException> testComponent(Type type, SegmentType.Field.Component profile) {
    List<ValidationException> exList = new ArrayList<>();
    UsageInfo usage = new UsageInfo(profile);
    exList.addAll(testType(type, profile.getDatatype(), usage, null));

    // test children
    try {//w  w w . ja v  a2 s  . c  om
        if (profile.getSubComponents().size() > 0 && !usage.disallowed() && !isEmpty(type)) {
            if (Composite.class.isAssignableFrom(type.getClass())) {
                Composite comp = (Composite) type;

                if (validateChildren) {
                    int i = 1;
                    for (SegmentType.Field.Component.SubComponent subComponent : profile.getSubComponents()) {
                        UsageInfo scUsage = new UsageInfo(subComponent);
                        try {
                            Type sub = comp.getComponent(i - 1);
                            exList.addAll(testType(sub, subComponent.getDatatype(), scUsage, null));
                        } catch (DataTypeException de) {
                            profileNotHL7Compliant(exList, SUBCOMPONENT_TYPE_MISMATCH, type.getName(), i);
                        }
                        ++i;
                    }
                }

                exList.addAll(checkUndefinedComponents(comp, profile.getSubComponents().size()));
            } else {
                profileViolatedWhen(true, exList, WRONG_COMPONENT_TYPE, type.getClass().getName());
            }
        }
    } catch (HL7Exception e) {
        exList.add(new ValidationException(e));
    }

    return exList;
}

From source file:org.evosuite.utils.generic.GenericTypeInference.java

private void addToMap(Type type, Type actualType, Map<TypeVariable<?>, Type> typeMap) {
    if (type instanceof ParameterizedType) {
        addToMap((ParameterizedType) type, actualType, typeMap);
    } else if (type instanceof TypeVariable<?>) {
        addToMap((TypeVariable<?>) type, actualType, typeMap);
    } else if (type instanceof GenericArrayType) {
        logger.info(// w ww .ja v a 2 s  .  c  o m
                "Is generic array with component type " + ((GenericArrayType) type).getGenericComponentType());
        logger.info("Actual type " + actualType + ", " + actualType.getClass());
        if (actualType instanceof GenericArrayType) {
            addToMap(((GenericArrayType) type).getGenericComponentType(),
                    ((GenericArrayType) actualType).getGenericComponentType(), typeMap);
        } else if (actualType instanceof Class<?> && ((Class<?>) actualType).isArray()) {
            addToMap(((GenericArrayType) type).getGenericComponentType(),
                    ((Class<?>) actualType).getComponentType(), typeMap);
        }
    } else {
        logger.info("Is unexpected type: " + type + ", " + type.getClass());
    }
}

From source file:com.proofpoint.jaxrs.SmileMapper.java

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream)
        throws IOException {
    JsonGenerator jsonGenerator = new SmileFactory().createGenerator(outputStream);

    // Important: we are NOT to close the underlying stream after
    // mapping, so we need to instruct generator:
    jsonGenerator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

    // 04-Mar-2010, tatu: How about type we were given? (if any)
    JavaType rootType = null;//w w  w . j  a v  a2 s  . c  o  m
    if (genericType != null && value != null) {
        // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root
        // type since it prevents polymorphic type serialization. Since we really
        // just need this for generics, let's only use generic type if it's truly
        // generic.
        if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type'
            // This is still not exactly right; should root type be further
            // specialized with 'value.getClass()'? Let's see how well this works before
            // trying to come up with more complete solution.
            rootType = objectMapper.getTypeFactory().constructType(genericType);
            // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where
            // type degenerates back into "Object.class" (as is the case with plain TypeVariable,
            // for example), and not use that.
            //
            if (rootType.getRawClass() == Object.class) {
                rootType = null;
            }
        }
    }

    if (rootType != null) {
        objectMapper.writerWithType(rootType).writeValue(jsonGenerator, value);
    } else {
        objectMapper.writeValue(jsonGenerator, value);
    }
}

From source file:io.airlift.jaxrs.SmileMapper.java

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream)
        throws IOException {
    JsonGenerator jsonGenerator = new SmileFactory().createGenerator(outputStream);

    // Important: we are NOT to close the underlying stream after
    // mapping, so we need to instruct generator:
    jsonGenerator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

    // 04-Mar-2010, tatu: How about type we were given? (if any)
    JavaType rootType = null;/*  ww w  .j a v a2s  . co m*/
    if (genericType != null && value != null) {
        // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root
        //    type since it prevents polymorphic type serialization. Since we really
        //    just need this for generics, let's only use generic type if it's truly
        //    generic.
        if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type'
            // This is still not exactly right; should root type be further
            // specialized with 'value.getClass()'? Let's see how well this works before
            // trying to come up with more complete solution.
            rootType = objectMapper.getTypeFactory().constructType(genericType);
            // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where
            //    type degenerates back into "Object.class" (as is the case with plain TypeVariable,
            //    for example), and not use that.
            //
            if (rootType.getRawClass() == Object.class) {
                rootType = null;
            }
        }
    }

    if (rootType != null) {
        objectMapper.writerWithType(rootType).writeValue(jsonGenerator, value);
    } else {
        objectMapper.writeValue(jsonGenerator, value);
    }
}

From source file:org.evosuite.utils.generic.GenericClass.java

private static boolean isMissingTypeParameters(Type type) {
    if (type instanceof Class) {
        for (Class<?> clazz = (Class<?>) type; clazz != null; clazz = clazz.getEnclosingClass()) {
            if (clazz.getTypeParameters().length != 0)
                return true;
        }/*from w w  w.  j  ava  2  s  .c  o  m*/
        return false;
    } else if (type instanceof ParameterizedType) {
        return false;
    } else {
        throw new AssertionError("Unexpected type " + type.getClass());
    }
}

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  o  m
    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:org.openehealth.ipf.gazelle.validation.core.GazelleProfileRule.java

/**
 * Tests a Type against the corresponding section of a profile.
 *
 * @param encoded optional encoded form of type (if you want to specify this -- if null, default
 *                pipe-encoded form is used to check length and constant val)
 *//*www .  j av  a  2  s.  c  om*/
protected List<ValidationException> testType(Type type, String dataType, UsageInfo usage, String encoded,
        boolean testUsage) {
    ArrayList<ValidationException> exList = new ArrayList<>();
    if (encoded == null)
        encoded = PipeParser.encode(type, this.enc);

    if (testUsage) {
        testUsage(exList, encoded, usage);
    }

    if (!usage.disallowed() && !encoded.isEmpty()) {
        // check datatype
        if ((type instanceof ca.uhn.hl7v2.model.v231.datatype.TSComponentOne
                || type instanceof ca.uhn.hl7v2.model.v24.datatype.TSComponentOne) && !dataType.equals("ST")) {
            profileNotHL7Compliant(exList, HL7_DATATYPE_MISMATCH, type.getName(), dataType);
        } else if (!(type instanceof TSComponentOne) && !type.getName().contains(dataType)) {
            profileViolatedWhen(
                    !(type.getClass().getSimpleName().equals("Varies")
                            || type.getClass().getSimpleName().equals("QIP")),
                    exList, HL7_DATATYPE_MISMATCH, type.getName(), dataType);
        }

        // check length
        profileViolatedWhen(encoded.length() > usage.length, exList, LENGTH_EXCEEDED, usage.name,
                encoded.length(), usage.length);

        // check constant value
        if (usage.constantValue != null && usage.constantValue.length() > 0) {
            profileViolatedWhen(!encoded.equals(usage.constantValue), exList, WRONG_CONSTANT_VALUE, encoded,
                    usage.constantValue);
        }

        // TODO : check against table, or do we need this check?
        // Gazelle checks code system and issues a WARNING if a check fails
    }

    return exList;
}

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

public Object executeMatcher(int i) throws IllegalArgumentException {
    if (i < 0 || i >= getNumberOfInputParameters()) {
        throw new IllegalArgumentException("Invalid index: " + i);
    }//from   www. j  a v  a2  s.c o  m

    Type[] types = method.getParameterTypes();
    Type type = types[i];

    try {
        if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
            return Mockito.anyInt();
        } else if (type.equals(Long.TYPE) || type.equals(Long.class)) {
            return Mockito.anyLong();
        } else if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
            return Mockito.anyBoolean();
        } else if (type.equals(Double.TYPE) || type.equals(Double.class)) {
            return Mockito.anyDouble();
        } else if (type.equals(Float.TYPE) || type.equals(Float.class)) {
            return Mockito.anyFloat();
        } else if (type.equals(Short.TYPE) || type.equals(Short.class)) {
            return Mockito.anyShort();
        } else if (type.equals(Character.TYPE) || type.equals(Character.class)) {
            return Mockito.anyChar();
        } else if (type.equals(String.class)) {
            return Mockito.anyString();
        } else {
            return Mockito.any(type.getClass());
        }
    } catch (Exception e) {
        logger.error("Failed to executed Mockito matcher n{} of type {} in {}.{}: {}", i, type, className,
                methodName, e.getMessage());
        throw new EvosuiteError(e);
    }
}