Example usage for java.lang.reflect Field getGenericType

List of usage examples for java.lang.reflect Field getGenericType

Introduction

In this page you can find the example usage for java.lang.reflect Field getGenericType.

Prototype

public Type getGenericType() 

Source Link

Document

Returns a Type object that represents the declared type for the field represented by this Field object.

Usage

From source file:org.mule.modules.servicesource.metadata.MetadataExtractor.java

public MetaDataModel describeModel(Map<String, MetaDataModel> model, Class<?> type, Field field) {
    DataType dataType = getDataType(type);
    MetaDataModel result = null;/*from w ww .  ja  v a  2  s . co  m*/

    if (DataType.POJO.equals(dataType)) {

        Map<String, MetaDataModel> cachedModel = this.pojoModelCache.get(type);

        if (cachedModel != null) {
            model = cachedModel;

        } else {

            this.pojoModelCache.put(type, model);

            for (Field pojoField : getFields(type)) {

                if (pojoField.getType() == null || Modifier.isStatic(pojoField.getModifiers())) {
                    continue; // this is a native type
                }

                String name = pojoField.getName();

                if ("extensions".equals(name) || "relationships".equals(name)) {
                    continue;
                } else {
                    SerializedName annotation = pojoField.getAnnotation(SerializedName.class);
                    name = annotation != null ? annotation.value() : pojoField.getName();
                }

                model.put(name, describeModel(newModelMap(), pojoField.getType(), pojoField));
            }
        }

        result = new DefaultDefinedMapMetaDataModel(model);

    } else if (DataType.MAP.equals(dataType)) {
        result = new DefaultParameterizedMapMetaDataModel(new DefaultSimpleMetaDataModel(DataType.STRING),
                new DefaultSimpleMetaDataModel(DataType.STRING));
        model.put(field.getName(), result);

    } else if (DataType.LIST.equals(dataType)) {

        Class<?> listType = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
        result = new DefaultListMetaDataModel(describeModel(newModelMap(), listType, field));
        model.put(field.getName(), result);

    } else {

        result = new DefaultSimpleMetaDataModel(dataType);
        model.put(field.getName(), result);
    }

    return result;
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Instantiates a new <code>FieldInfo</code> object not part of a defined
 * table.//from www  . jav  a  2s  .  c  o  m
 *
 * @author vasu
 *
 * @param  cinfo the non-<code>null</code> class info for the POJO
 * @param  field the non-<code>null</code> field to create an info object for
 * @throws IllegalArgumentException if unable to find a getter or setter
 *         method for the field of if improperly annotated
 */
FieldInfoImpl(ClassInfoImpl<T> cinfo, Field field) {
    this.clazz = cinfo.getObjectClass();
    this.cinfo = cinfo;
    this.tinfo = null;
    this.declaringClass = field.getDeclaringClass();
    this.field = field;
    field.setAccessible(true); // make it accessible in case we need to
    this.isFinal = Modifier.isFinal(field.getModifiers());
    this.name = field.getName();
    this.type = DataTypeImpl.unwrapOptionalIfPresent(field.getType(), field.getGenericType());
    this.column = null;
    this.persisted = null;
    this.persister = null;
    this.suffix = field.getAnnotation(SuffixKey.class);
    this.mandatory = true; // keyspace suffixes are mandatory fields
    this.index = null; // we don't care about this for keyspace suffixes
    this.partitionKey = null; // we don't care about this for keyspace suffixes
    this.clusteringKey = null; // we don't care about this for keyspace suffixes
    this.typeKey = null; // we don't care about this for keyspace suffixes
    this.multiKeyType = null; // we don't care about this for keyspace suffixes
    this.definition = null; // we don't care about this for keyspace suffixes
    this.decoder = null; // we don't care about this for keyspace suffixes
    this.getter = findGetterMethod(declaringClass);
    this.setter = findSetterMethod(declaringClass);
    this.finalValue = findFinalValue();
}

From source file:org.raml.emitter.RamlEmitterV2.java

/**
 * <p>dumpMappingField.</p>//from w  ww. j av  a2  s .  com
 *
 * @param dump a {@link java.lang.StringBuilder} object.
 * @param depth a int.
 * @param field a {@link java.lang.reflect.Field} object.
 * @param implicit a boolean.
 * @param pojo a {@link java.lang.Object} object.
 * @param inlineLists a boolean.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void dumpMappingField(StringBuilder dump, int depth, Field field, boolean implicit, Object pojo,
        boolean inlineLists) {
    if (!Map.class.isAssignableFrom(field.getType())) {
        throw new RuntimeException("invalid type");
    }

    Map value = (Map) getFieldValue(field, pojo);
    MapFilter annotation = field.getAnnotation(MapFilter.class);
    if (annotation != null) {
        try {
            IFilter newInstance = annotation.value().newInstance();
            LinkedHashMap q = new LinkedHashMap();
            for (Object a : value.keySet()) {
                Object object = value.get(a);
                if (newInstance.accept(object)) {
                    q.put(a, object);
                }
            }
            value = q;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    if (value == null || value.isEmpty()) {
        return;
    }
    boolean isSettings = false;
    if (field.getName().equals("settings")) {
        isSettings = true;
    }

    if (!implicit) {
        dump.append(indent(depth)).append(alias(field)).append(YAML_MAP_SEP).append("\n");
        depth++;
    }

    ParameterizedType pType = (ParameterizedType) field.getGenericType();
    Type valueType = pType.getActualTypeArguments()[1];
    dumpMap(dump, depth, valueType, value, isSettings, false);
}

From source file:play.modules.scaffold.strategy.JpaViewScaffoldingStrategy.java

@Override
public FormElement render(Field field) {
    FormElement defaultValue = super.render(field);
    if (defaultValue == null)
        return null;
    // get the list of annotations
    List<Class<? extends Annotation>> annotations = Fields.annotations(field);
    // also get the list of the names of the annotations -- this is a little
    // redundant, but the reason we do this is because different versions of
    // Play! support different versions of JPA, and we can't know at compile
    // time which classes will be available... particularly, we currently
    // support Play! 1.0 which uses JPA 1 and therefore won't have the
    // ElementCollection annotation, while Play! 1.1, which uses JPA 2,
    // does.//from w w  w.j  av a2  s . c  om
    List<String> annotationNames = Fields.annotationNames(field);
    if (defaultValue.getType() == FormElementType.TEXT && annotations.contains(javax.persistence.Lob.class)) {
        return new FormElement(defaultValue, FormElementType.TEXTAREA);
    }
    if (annotations.contains(javax.persistence.Id.class)) {
        return new FormElement(defaultValue, FormElementType.HIDDEN);
    } else if (annotations.contains(javax.persistence.Embedded.class)) {
        return new FormElement(defaultValue, FormElementType.EMBEDDED);
    } else if (annotations.contains(javax.persistence.OneToOne.class)) {
        OneToOne ann = field.getAnnotation(OneToOne.class);
        if (!StringUtils.isEmpty(ann.mappedBy())) {
            return null;
        }
        return new FormElement(defaultValue, FormElementType.RELATION);
    } else if (annotations.contains(javax.persistence.ManyToOne.class)) {
        return new FormElement(defaultValue, FormElementType.RELATION);
    }
    if (Collection.class.isAssignableFrom(field.getType())) {
        Class<?> parameterizedType = (Class<?>) ((ParameterizedType) field.getGenericType())
                .getActualTypeArguments()[0];
        if (annotationNames.contains("javax.persistence.ElementCollection")
                || annotationNames.contains("org.hibernate.annotations.CollectionOfElements")) {
            return new FormElement(defaultValue, parameterizedType, FormElementType.LIST);
        }
        if (annotations.contains(javax.persistence.OneToMany.class)) {
            OneToMany ann = field.getAnnotation(OneToMany.class);
            if (!StringUtils.isEmpty(ann.mappedBy())) {
                return null;
            }
            return new FormElement(defaultValue, parameterizedType, FormElementType.RELATION).acceptMultiple();
        }
        if (annotations.contains(javax.persistence.ManyToMany.class)) {
            ManyToMany ann = field.getAnnotation(ManyToMany.class);
            if (!StringUtils.isEmpty(ann.mappedBy())) {
                return null;
            }
            return new FormElement(defaultValue, parameterizedType, FormElementType.RELATION).acceptMultiple();
        }
    }
    return defaultValue;
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getObject(Class claz, List<Type> heirarchies) throws Exception {

    if (claz.isEnum())
        return claz.getEnumConstants()[0];

    if (isMap(claz)) {
        return getMapValue(claz, claz.getTypeParameters(), heirarchies);
    } else if (isCollection(claz)) {
        return getListSetValue(claz, claz.getTypeParameters(), heirarchies);
    } else if (claz.isInterface() || Modifier.isAbstract(claz.getModifiers())) {
        return null;
    }/*  ww  w.  j  a  va2s.c om*/

    if (heirarchies.contains(claz) || heirarchies.size() >= 2)
        return null;
    heirarchies.add(claz);

    Constructor cons = null;
    try {
        cons = claz.getConstructor(new Class[] {});
    } catch (Exception e) {
        getLog().error("No public no-args constructor found for class " + claz.getName());
        return null;
    }

    Object object = cons.newInstance(new Object[] {});
    List<Field> allFields = getAllFields(claz);

    for (Field field : allFields) {

        if (Modifier.isStatic(field.getModifiers()))
            continue;

        if (!field.isAccessible()) {
            field.setAccessible(true);
        }

        List<Type> fheirlst = new ArrayList<Type>(heirarchies);

        if (isDebugEnabled())
            getLog().info("Parsing Class " + getHeirarchyStr(fheirlst) + " field " + field.getName() + " type "
                    + field.getType().equals(boolean.class));

        if (isPrimitive(field.getType())) {
            field.set(object, getPrimitiveValue(field.getType()));
        } else if (isMap(field.getType())) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            field.set(object, getMapValue(field.getType(), type.getActualTypeArguments(), fheirlst));
        } else if (isCollection(field.getType())) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            field.set(object, getListSetValue(field.getType(), type.getActualTypeArguments(), fheirlst));
        } else if (!claz.equals(field.getType())) {
            Object fieldval = getObject(field.getType(), fheirlst);
            field.set(object, fieldval);
        } else if (claz.equals(field.getType())) {
            if (isDebugEnabled())
                getLog().info("Ignoring recursive fields...");
        }
    }
    return object;
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Instantiates a new <code>FieldInfo</code> object as a column part of a
 * defined table.//from  w  ww .  j  ava 2s. c o  m
 *
 * @author vasu
 *
 * @param  tinfo the table info for the field
 * @param  field the non-<code>null</code> field to create an info object for
 * @throws IllegalArgumentException if unable to find a getter or setter
 *         method for the field of if improperly annotated
 */
FieldInfoImpl(TableInfoImpl<T> tinfo, Field field) {
    this.clazz = tinfo.getObjectClass();
    this.cinfo = (ClassInfoImpl<T>) tinfo.getClassInfo();
    this.tinfo = tinfo;
    this.declaringClass = field.getDeclaringClass();
    this.field = field;
    field.setAccessible(true); // make it accessible in case we need to
    this.isFinal = Modifier.isFinal(field.getModifiers());
    this.name = field.getName();
    this.type = DataTypeImpl.unwrapOptionalIfPresent(field.getType(), field.getGenericType());
    this.persisted = field.getAnnotation(Persisted.class);
    if (persisted != null) {
        org.apache.commons.lang3.Validate.isTrue(
                (persisted.as() != DataType.INFERRED) && !persisted.as().isCollection(),
                "@Persisted annotation cannot be of type '%s': %s.%s", persisted.as(), declaringClass.getName(),
                field.getName());
        this.persister = newPersister();
    } else {
        this.persister = null;
    }
    this.suffix = field.getAnnotation(SuffixKey.class);
    this.mandatory = field.getAnnotation(Mandatory.class) != null;
    final Map<String, Column> columns = ReflectionUtils.getAnnotationsByType(String.class, Column.class, field);
    final Map<String, Index> indexes = ReflectionUtils.getAnnotationsByType(String.class, Index.class, field);
    final Map<String, PartitionKey> partitionKeys = ReflectionUtils.getAnnotationsByType(String.class,
            PartitionKey.class, field);
    final Map<String, ClusteringKey> clusteringKeys = ReflectionUtils.getAnnotationsByType(String.class,
            ClusteringKey.class, field);
    final Map<String, TypeKey> typeKeys = ReflectionUtils.getAnnotationsByType(String.class, TypeKey.class,
            field);
    final boolean isInTable = tinfo.getTable() != null;

    if (isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!(!indexes.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @Index: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!partitionKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @PartitionKey: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!clusteringKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @ClusteringKey: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!typeKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @TypeKey: %s.%s",
                declaringClass.getName(), field.getName());
    }
    // Note: while searching for the matching table, uses the name from the
    // table annotation instead of the one returned by getName() as the later
    // might have been cleaned and hence would not match what was defined in
    // the POJO
    final String tname = isInTable ? tinfo.getTable().name() : Table.ALL;

    Column column = columns.get(tname);
    Index index = indexes.get(tname);
    PartitionKey partitionKey = partitionKeys.get(tname);
    ClusteringKey clusteringKey = clusteringKeys.get(tname);
    TypeKey typeKey = typeKeys.get(tname);

    if (column == null) { // fallback to special Table.ALL name
        column = columns.get(Table.ALL);
    }
    this.column = column;
    if (index == null) { // fallback to special Table.ALL name
        index = indexes.get(Table.ALL);
    }
    this.index = index;
    if (partitionKey == null) { // fallback to special Table.ALL name
        partitionKey = partitionKeys.get(Table.ALL);
    }
    this.partitionKey = partitionKey;
    if (clusteringKey == null) { // fallback to special Table.ALL name
        clusteringKey = clusteringKeys.get(Table.ALL);
    }
    this.clusteringKey = clusteringKey;
    if (typeKey == null) { // fallback to special Table.ALL name
        typeKey = typeKeys.get(Table.ALL);
    }
    this.typeKey = typeKey;
    // validate some UDT stuff
    if (!isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!isIndex(), "field cannot be annotated with @Index: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isPartitionKey(),
                "field cannot be annotated with @PartitionKey: %s.%s", declaringClass.getName(),
                field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isClusteringKey(),
                "field cannot be annotated with @ClusteringKey: %s.%s", declaringClass.getName(),
                field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isTypeKey(), "field cannot be annotated with @TypeKey: %s.%s",
                declaringClass.getName(), field.getName());
    }
    if (isColumn()) {
        this.definition = DataTypeImpl.inferDataTypeFrom(field);
        this.decoder = definition.getDecoder(field, isMandatory() || isPartitionKey() || isClusteringKey());
        if (isInTable && ((clusteringKey != null) || (partitionKey != null))
                && (definition.getType() == DataType.SET)) {
            final Type type = field.getGenericType();

            if (type instanceof ParameterizedType) {
                final ParameterizedType ptype = (ParameterizedType) type;

                this.multiKeyType = ReflectionUtils.getRawClass(ptype.getActualTypeArguments()[0]); // sets will always have 1 argument
            } else {
                throw new IllegalArgumentException(
                        "unable to determine the element type of multi-field in table '" + tname + "': "
                                + declaringClass.getName() + "." + field.getName());
            }
        } else {
            this.multiKeyType = null;
        }
    } else {
        this.definition = null;
        this.decoder = null;
        this.multiKeyType = null;
    }
    this.getter = findGetterMethod(declaringClass);
    this.setter = findSetterMethod(declaringClass);
    this.finalValue = findFinalValue();
    // validate some stuff
    if (isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!(isIndex() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @Index: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isPartitionKey() && isClusteringKey()),
                "field in table '%s' must not be annotated with @ClusteringKey if it is annotated with @PartitionKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isPartitionKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @PartitionKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isClusteringKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @ClusteringKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @TypeKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && !String.class.equals(getType())),
                "field in table '%s' must be a String if it is annotated with @TypeKey: %s.%s", tname,
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && isFinal()),
                "field in table '%s' must not be final if it is annotated with @TypeKey: %s.%s", tname,
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(
                !(isTypeKey() && !(cinfo instanceof RootClassInfoImpl)
                        && !(cinfo instanceof TypeClassInfoImpl)),
                "field in table '%s' must not be annotated with @TypeKey if class is annotated with @Entity: %s.%s",
                tname, declaringClass.getName(), field.getName());
        if (isColumn() && definition.isCollection()) {
            org.apache.commons.lang3.Validate.isTrue(
                    !((isClusteringKey() || isPartitionKey()) && (multiKeyType == null)),
                    "field in table '%s' cannot be '%s' if it is annotated with @ClusteringKey or @PartitionKey: %s.%s",
                    tname, definition, declaringClass.getName(), field.getName());
        }
    }
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

@SuppressWarnings("unchecked")
protected <OUT, IN1, IN2> TypeInformation<OUT> analyzePojo(Class<OUT> clazz, ArrayList<Type> typeHierarchy,
        ParameterizedType parameterizedType, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) {

    if (!Modifier.isPublic(clazz.getModifiers())) {
        LOG.info("Class " + clazz.getName()
                + " is not public, cannot treat it as a POJO type. Will be handled as GenericType");
        return new GenericTypeInfo<OUT>(clazz);
    }/*w  w  w . ja v a  2 s  . c om*/

    // add the hierarchy of the POJO itself if it is generic
    if (parameterizedType != null) {
        getTypeHierarchy(typeHierarchy, parameterizedType, Object.class);
    }
    // create a type hierarchy, if the incoming only contains the most bottom one or none.
    else if (typeHierarchy.size() <= 1) {
        getTypeHierarchy(typeHierarchy, clazz, Object.class);
    }

    List<Field> fields = getAllDeclaredFields(clazz, false);
    if (fields.size() == 0) {
        LOG.info("No fields detected for " + clazz
                + ". Cannot be used as a PojoType. Will be handled as GenericType");
        return new GenericTypeInfo<OUT>(clazz);
    }

    List<PojoField> pojoFields = new ArrayList<PojoField>();
    for (Field field : fields) {
        Type fieldType = field.getGenericType();
        if (!isValidPojoField(field, clazz, typeHierarchy)) {
            LOG.info(clazz + " is not a valid POJO type");
            return null;
        }
        try {
            ArrayList<Type> fieldTypeHierarchy = new ArrayList<Type>(typeHierarchy);
            fieldTypeHierarchy.add(fieldType);
            TypeInformation<?> ti = createTypeInfoWithTypeHierarchy(fieldTypeHierarchy, fieldType, in1Type,
                    in2Type);
            pojoFields.add(new PojoField(field, ti));
        } catch (InvalidTypesException e) {
            Class<?> genericClass = Object.class;
            if (isClassType(fieldType)) {
                genericClass = typeToClass(fieldType);
            }
            pojoFields.add(new PojoField(field, new GenericTypeInfo<OUT>((Class<OUT>) genericClass)));
        }
    }

    CompositeType<OUT> pojoType = new PojoTypeInfo<OUT>(clazz, pojoFields);

    //
    // Validate the correctness of the pojo.
    // returning "null" will result create a generic type information.
    //
    List<Method> methods = getAllDeclaredMethods(clazz);
    for (Method method : methods) {
        if (method.getName().equals("readObject") || method.getName().equals("writeObject")) {
            LOG.info(clazz + " contains custom serialization methods we do not call.");
            return null;
        }
    }

    // Try retrieving the default constructor, if it does not have one
    // we cannot use this because the serializer uses it.
    Constructor defaultConstructor = null;
    try {
        defaultConstructor = clazz.getDeclaredConstructor();
    } catch (NoSuchMethodException e) {
        if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
            LOG.info(clazz + " is abstract or an interface, having a concrete "
                    + "type can increase performance.");
        } else {
            LOG.info(clazz + " must have a default constructor to be used as a POJO.");
            return null;
        }
    }
    if (defaultConstructor != null && !Modifier.isPublic(defaultConstructor.getModifiers())) {
        LOG.info("The default constructor of " + clazz + " should be Public to be used as a POJO.");
        return null;
    }

    // everything is checked, we return the pojo
    return pojoType;
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

/**
 * Finds the type information to a type variable.
 *
 * It solve the following://from ww  w  .  j av a 2  s.  c  o m
 *
 * Return the type information for "returnTypeVar" given that "inType" has type information "inTypeInfo".
 * Thus "inType" must contain "returnTypeVar" in a "inputTypeHierarchy", otherwise null is returned.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private <IN1> TypeInformation<?> createTypeInfoFromInput(TypeVariable<?> returnTypeVar,
        ArrayList<Type> inputTypeHierarchy, Type inType, TypeInformation<IN1> inTypeInfo) {
    TypeInformation<?> info = null;

    // use a factory to find corresponding type information to type variable
    final ArrayList<Type> factoryHierarchy = new ArrayList<>(inputTypeHierarchy);
    final TypeInfoFactory<?> factory = getClosestFactory(factoryHierarchy, inType);
    if (factory != null) {
        // the type that defines the factory is last in factory hierarchy
        final Type factoryDefiningType = factoryHierarchy.get(factoryHierarchy.size() - 1);
        // defining type has generics, the factory need to be asked for a mapping of subtypes to type information
        if (factoryDefiningType instanceof ParameterizedType) {
            final Type[] typeParams = typeToClass(factoryDefiningType).getTypeParameters();
            final Type[] actualParams = ((ParameterizedType) factoryDefiningType).getActualTypeArguments();
            // go thru all elements and search for type variables
            for (int i = 0; i < actualParams.length; i++) {
                final Map<String, TypeInformation<?>> componentInfo = inTypeInfo.getGenericParameters();
                final String typeParamName = typeParams[i].toString();
                if (!componentInfo.containsKey(typeParamName) || componentInfo.get(typeParamName) == null) {
                    throw new InvalidTypesException("TypeInformation '" + inTypeInfo.getClass().getSimpleName()
                            + "' does not supply a mapping of TypeVariable '" + typeParamName
                            + "' to corresponding TypeInformation. "
                            + "Input type inference can only produce a result with this information. "
                            + "Please implement method 'TypeInformation.getGenericParameters()' for this.");
                }
                info = createTypeInfoFromInput(returnTypeVar, factoryHierarchy, actualParams[i],
                        componentInfo.get(typeParamName));
                if (info != null) {
                    break;
                }
            }
        }
    }
    // the input is a type variable
    else if (sameTypeVars(inType, returnTypeVar)) {
        return inTypeInfo;
    } else if (inType instanceof TypeVariable) {
        Type resolvedInType = materializeTypeVariable(inputTypeHierarchy, (TypeVariable<?>) inType);
        if (resolvedInType != inType) {
            info = createTypeInfoFromInput(returnTypeVar, inputTypeHierarchy, resolvedInType, inTypeInfo);
        }
    }
    // input is an array
    else if (inType instanceof GenericArrayType) {
        TypeInformation<?> componentInfo = null;
        if (inTypeInfo instanceof BasicArrayTypeInfo) {
            componentInfo = ((BasicArrayTypeInfo<?, ?>) inTypeInfo).getComponentInfo();
        } else if (inTypeInfo instanceof PrimitiveArrayTypeInfo) {
            componentInfo = BasicTypeInfo.getInfoFor(inTypeInfo.getTypeClass().getComponentType());
        } else if (inTypeInfo instanceof ObjectArrayTypeInfo) {
            componentInfo = ((ObjectArrayTypeInfo<?, ?>) inTypeInfo).getComponentInfo();
        }
        info = createTypeInfoFromInput(returnTypeVar, inputTypeHierarchy,
                ((GenericArrayType) inType).getGenericComponentType(), componentInfo);
    }
    // the input is a tuple
    else if (inTypeInfo instanceof TupleTypeInfo && isClassType(inType)
            && Tuple.class.isAssignableFrom(typeToClass(inType))) {
        ParameterizedType tupleBaseClass;

        // get tuple from possible tuple subclass
        while (!(isClassType(inType) && typeToClass(inType).getSuperclass().equals(Tuple.class))) {
            inputTypeHierarchy.add(inType);
            inType = typeToClass(inType).getGenericSuperclass();
        }
        inputTypeHierarchy.add(inType);

        // we can assume to be parameterized since we
        // already did input validation
        tupleBaseClass = (ParameterizedType) inType;

        Type[] tupleElements = tupleBaseClass.getActualTypeArguments();
        // go thru all tuple elements and search for type variables
        for (int i = 0; i < tupleElements.length; i++) {
            info = createTypeInfoFromInput(returnTypeVar, inputTypeHierarchy, tupleElements[i],
                    ((TupleTypeInfo<?>) inTypeInfo).getTypeAt(i));
            if (info != null) {
                break;
            }
        }
    }
    // the input is a pojo
    else if (inTypeInfo instanceof PojoTypeInfo && isClassType(inType)) {
        // build the entire type hierarchy for the pojo
        getTypeHierarchy(inputTypeHierarchy, inType, Object.class);
        // determine a field containing the type variable
        List<Field> fields = getAllDeclaredFields(typeToClass(inType), false);
        for (Field field : fields) {
            Type fieldType = field.getGenericType();
            if (fieldType instanceof TypeVariable && sameTypeVars(returnTypeVar,
                    materializeTypeVariable(inputTypeHierarchy, (TypeVariable<?>) fieldType))) {
                return getTypeOfPojoField(inTypeInfo, field);
            } else if (fieldType instanceof ParameterizedType || fieldType instanceof GenericArrayType) {
                ArrayList<Type> typeHierarchyWithFieldType = new ArrayList<>(inputTypeHierarchy);
                typeHierarchyWithFieldType.add(fieldType);
                TypeInformation<?> foundInfo = createTypeInfoFromInput(returnTypeVar,
                        typeHierarchyWithFieldType, fieldType, getTypeOfPojoField(inTypeInfo, field));
                if (foundInfo != null) {
                    return foundInfo;
                }
            }
        }
    }
    return info;
}

From source file:org.evosuite.setup.TestClusterGenerator.java

private boolean addDependencyClass(GenericClass clazz, int recursionLevel) {
    if (recursionLevel > Properties.CLUSTER_RECURSION) {
        logger.debug("Maximum recursion level reached, not adding dependency {}", clazz.getClassName());
        return false;
    }//from   ww  w.  j  av  a  2s  .  c o  m

    clazz = clazz.getRawGenericClass();

    if (analyzedClasses.contains(clazz.getRawClass())) {
        return true;
    }
    analyzedClasses.add(clazz.getRawClass());

    // We keep track of generic containers in case we find other concrete generic components during runtime
    if (clazz.isAssignableTo(Collection.class) || clazz.isAssignableTo(Map.class)) {
        if (clazz.getNumParameters() > 0) {
            containerClasses.add(clazz.getRawClass());
        }
    }

    if (clazz.equals(String.class)) {
        return false;
    }

    try {
        TestCluster cluster = TestCluster.getInstance();
        logger.debug("Adding dependency class {}", clazz.getClassName());

        // TODO: Should we include declared classes as well?

        if (!canUse(clazz.getRawClass())) {
            logger.info("*** Cannot use class: {}", clazz.getClassName());
            return false;
        }

        // Add all constructors
        for (Constructor<?> constructor : getConstructors(clazz.getRawClass())) {
            String name = "<init>" + org.objectweb.asm.Type.getConstructorDescriptor(constructor);

            if (Properties.TT) {
                String orig = name;
                name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(), "<init>",
                        org.objectweb.asm.Type.getConstructorDescriptor(constructor));
                if (!orig.equals(name))
                    logger.info("TT name: {} -> {}", orig, name);

            }

            if (canUse(constructor)) {
                GenericConstructor genericConstructor = new GenericConstructor(constructor, clazz);
                try {
                    cluster.addGenerator(clazz.getWithWildcardTypes(), genericConstructor);
                    addDependencies(genericConstructor, recursionLevel + 1);
                    logger.debug("Keeping track of {}.{}{}", constructor.getDeclaringClass().getName(),
                            constructor.getName(), Type.getConstructorDescriptor(constructor));
                } catch (Throwable t) {
                    logger.info("Error adding constructor {}: {}", constructor.getName(), t.getMessage());
                }

            } else {
                logger.debug("Constructor cannot be used: {}", constructor);
            }

        }

        // Add all methods
        for (Method method : getMethods(clazz.getRawClass())) {
            String name = method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method);

            if (Properties.TT) {
                String orig = name;
                name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(),
                        method.getName(), org.objectweb.asm.Type.getMethodDescriptor(method));
                if (!orig.equals(name))
                    logger.info("TT name: {} -> {}", orig, name);
            }

            if (canUse(method, clazz.getRawClass()) && !method.getName().equals("hashCode")) {
                logger.debug("Adding method {}.{}{}", clazz.getClassName(), method.getName(),
                        Type.getMethodDescriptor(method));

                if (method.getTypeParameters().length > 0) {
                    logger.info("Type parameters in methods are not handled yet, skipping {}", method);
                    continue;
                }
                GenericMethod genericMethod = new GenericMethod(method, clazz);
                try {
                    addDependencies(genericMethod, recursionLevel + 1);
                    cluster.addModifier(clazz.getWithWildcardTypes(), genericMethod);
                    //               GenericClass retClass = new GenericClass(
                    //                       genericMethod.getReturnType(), method.getReturnType());
                    GenericClass retClass = new GenericClass(method.getReturnType());

                    if (!retClass.isPrimitive() && !retClass.isVoid() && !retClass.isObject()) {
                        cluster.addGenerator(retClass.getWithWildcardTypes(), genericMethod);
                    }
                } catch (Throwable t) {
                    logger.info("Error adding method {}: {}", method.getName(), t.getMessage());
                }
            } else {
                logger.debug("Method cannot be used: {}", method);
            }
        }

        // Add all fields
        for (Field field : getFields(clazz.getRawClass())) {
            logger.debug("Checking field {}", field);
            if (canUse(field, clazz.getRawClass())) {
                logger.debug("Adding field {} for class {}", field, clazz);
                try {
                    GenericField genericField = new GenericField(field, clazz);
                    cluster.addGenerator(new GenericClass(field.getGenericType()).getWithWildcardTypes(),
                            genericField);
                    if (!Modifier.isFinal(field.getModifiers())) {
                        cluster.addModifier(clazz.getWithWildcardTypes(), genericField);
                        addDependencies(genericField, recursionLevel + 1);
                    }
                } catch (Throwable t) {
                    logger.info("Error adding field {}: {}", field.getName(), t.getMessage());
                }

            } else {
                logger.debug("Field cannot be used: {}", field);
            }
        }
        logger.info("Finished analyzing {} at recursion level {}", clazz.getTypeName(), recursionLevel);
        cluster.getAnalyzedClasses().add(clazz.getRawClass());
    } catch (Throwable t) {
        /*
         * NOTE: this is a problem we know it can happen in some cases in SF110, but don't
         * have a real solution now. As it is bound to happen, we try to minimize the logging (eg no
         * stack trace), although we still need to log it
         */
        logger.error("Problem for {}. Failed to add dependencies for class {}: {}\n{}", Properties.TARGET_CLASS,
                clazz.getClassName(), t, Arrays.asList(t.getStackTrace()));

        return false;
    }
    return true;
}

From source file:org.evosuite.setup.TestClusterGenerator.java

/**
 * All public methods defined directly in the SUT should be covered
 * //from ww  w .  jav a  2 s.c o m
 * TODO: What if we use instrument_parent?
 * 
 * @param targetClass
 */
@SuppressWarnings("unchecked")
private void initializeTargetMethods() throws RuntimeException, ClassNotFoundException {

    logger.info("Analyzing target class");
    Class<?> targetClass = Properties.getTargetClass();

    TestCluster cluster = TestCluster.getInstance();

    Set<Class<?>> targetClasses = new LinkedHashSet<Class<?>>();
    if (targetClass == null) {
        throw new RuntimeException("Failed to load " + Properties.TARGET_CLASS);
    }
    targetClasses.add(targetClass);
    addDeclaredClasses(targetClasses, targetClass);
    if (Modifier.isAbstract(targetClass.getModifiers())) {
        logger.info("SUT is an abstract class");
        Set<Class<?>> subclasses = getConcreteClasses(targetClass, inheritanceTree);
        logger.info("Found {} concrete subclasses", subclasses.size());
        targetClasses.addAll(subclasses);
    }

    // To make sure we also have anonymous inner classes double check inner classes using ASM
    ClassNode targetClassNode = DependencyAnalysis.getClassNode(Properties.TARGET_CLASS);
    Queue<InnerClassNode> innerClasses = new LinkedList<InnerClassNode>();
    innerClasses.addAll(targetClassNode.innerClasses);
    while (!innerClasses.isEmpty()) {
        InnerClassNode icn = innerClasses.poll();
        try {
            logger.debug("Loading inner class: {}, {},{}", icn.innerName, icn.name, icn.outerName);
            String innerClassName = ResourceList.getClassNameFromResourcePath(icn.name);
            Class<?> innerClass = TestGenerationContext.getInstance().getClassLoaderForSUT()
                    .loadClass(innerClassName);
            //if (!canUse(innerClass))
            //   continue;

            // Sometimes strange things appear such as Map$Entry
            if (!targetClasses.contains(innerClass)) {
                //                  && !innerClassName.matches(".*\\$\\d+(\\$.*)?$")) {

                logger.info("Adding inner class {}", innerClassName);
                targetClasses.add(innerClass);
                ClassNode innerClassNode = DependencyAnalysis.getClassNode(innerClassName);
                innerClasses.addAll(innerClassNode.innerClasses);
            }

        } catch (Throwable t) {
            logger.error("Problem for {}. Error loading inner class: {}, {},{}: {}", Properties.TARGET_CLASS,
                    icn.innerName, icn.name, icn.outerName, t);
        }
    }

    for (Class<?> clazz : targetClasses) {
        logger.info("Current SUT class: {}", clazz);

        if (!canUse(clazz)) {
            logger.info("Cannot access SUT class: {}", clazz);
            continue;
        }

        // Add all constructors
        for (Constructor<?> constructor : getConstructors(clazz)) {
            logger.info("Checking target constructor {}", constructor);
            String name = "<init>" + org.objectweb.asm.Type.getConstructorDescriptor(constructor);

            if (Properties.TT) {
                String orig = name;
                name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getName(), "<init>",
                        org.objectweb.asm.Type.getConstructorDescriptor(constructor));
                if (!orig.equals(name))
                    logger.info("TT name: {} -> {}", orig, name);

            }

            if (canUse(constructor)) {
                GenericConstructor genericConstructor = new GenericConstructor(constructor, clazz);
                cluster.addTestCall(genericConstructor);
                // TODO: Add types!
                cluster.addGenerator(new GenericClass(clazz).getWithWildcardTypes(), genericConstructor);
                addDependencies(genericConstructor, 1);
                logger.debug("Keeping track of {}.{}{}", constructor.getDeclaringClass().getName(),
                        constructor.getName(), Type.getConstructorDescriptor(constructor));
            } else {
                logger.debug("Constructor cannot be used: {}", constructor);
            }

        }

        // Add all methods
        for (Method method : getMethods(clazz)) {
            logger.info("Checking target method {}", method);
            String name = method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method);

            if (Properties.TT) {
                String orig = name;
                name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getName(), method.getName(),
                        org.objectweb.asm.Type.getMethodDescriptor(method));
                if (!orig.equals(name))
                    logger.info("TT name: {} -> {}", orig, name);
            }

            if (canUse(method, clazz)) {
                logger.debug("Adding method {}.{}{}", clazz.getName(), method.getName(),
                        Type.getMethodDescriptor(method));

                GenericMethod genericMethod = new GenericMethod(method, clazz);
                cluster.addTestCall(genericMethod);
                cluster.addModifier(new GenericClass(clazz).getWithWildcardTypes(), genericMethod);
                addDependencies(genericMethod, 1);
                GenericClass retClass = new GenericClass(method.getReturnType());

                if (!retClass.isPrimitive() && !retClass.isVoid() && !retClass.isObject())
                    cluster.addGenerator(retClass.getWithWildcardTypes(), genericMethod);
            } else {
                logger.debug("Method cannot be used: {}", method);
            }
        }

        for (Field field : getFields(clazz)) {
            logger.info("Checking target field {}", field);

            if (canUse(field, clazz)) {
                GenericField genericField = new GenericField(field, clazz);
                addDependencies(genericField, 1);
                cluster.addGenerator(new GenericClass(field.getGenericType()).getWithWildcardTypes(),
                        genericField);
                logger.debug("Adding field {}", field);
                if (!Modifier.isFinal(field.getModifiers())) {
                    logger.debug("Is not final");
                    cluster.addTestCall(new GenericField(field, clazz));
                } else {
                    logger.debug("Is final");
                    if (Modifier.isStatic(field.getModifiers()) && !field.getType().isPrimitive()) {
                        logger.debug("Is static non-primitive");
                        /* 
                         * With this we are trying to cover such cases:
                         * 
                        public static final DurationField INSTANCE = new MillisDurationField();
                                
                        private MillisDurationField() {
                        super();
                        }
                         */
                        try {
                            Object o = field.get(null);
                            if (o == null) {
                                logger.info("Field is not yet initialized: {}", field);
                            } else {
                                Class<?> actualClass = o.getClass();
                                logger.debug("Actual class is {}", actualClass);
                                if (!actualClass.isAssignableFrom(genericField.getRawGeneratedType())
                                        && genericField.getRawGeneratedType().isAssignableFrom(actualClass)) {
                                    GenericField superClassField = new GenericField(field, clazz);
                                    cluster.addGenerator(new GenericClass(actualClass), superClassField);
                                }
                            }
                        } catch (IllegalAccessException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                }
            } else {
                logger.debug("Can't use field {}", field);
            }
        }
        analyzedClasses.add(clazz);
        // TODO: Set to generic type rather than class?
        cluster.getAnalyzedClasses().add(clazz);
    }
    if (Properties.INSTRUMENT_PARENT) {
        for (String superClass : inheritanceTree.getSuperclasses(Properties.TARGET_CLASS)) {
            try {
                Class<?> superClazz = TestGenerationContext.getInstance().getClassLoaderForSUT()
                        .loadClass(superClass);
                dependencies.add(new Pair(0, superClazz));
            } catch (ClassNotFoundException e) {
                logger.error("Problem for {}. Class not found: {}", Properties.TARGET_CLASS, superClass, e);
            }

        }
    }

    if (Properties.HANDLE_STATIC_FIELDS) {

        GetStaticGraph getStaticGraph = GetStaticGraphGenerator.generate(Properties.TARGET_CLASS);

        Map<String, Set<String>> staticFields = getStaticGraph.getStaticFields();
        for (String className : staticFields.keySet()) {
            logger.info("Adding static fields to cluster for class {}", className);

            Class<?> clazz;
            try {
                clazz = getClass(className);
            } catch (ExceptionInInitializerError ex) {
                logger.debug("Class class init caused exception {}", className);
                continue;
            }
            if (clazz == null) {
                logger.debug("Class not found {}", className);
                continue;
            }

            if (!canUse(clazz))
                continue;

            Set<String> fields = staticFields.get(className);
            for (Field field : getFields(clazz)) {
                if (!canUse(field, clazz))
                    continue;

                if (fields.contains(field.getName())) {
                    if (!Modifier.isFinal(field.getModifiers())) {
                        logger.debug("Is not final");
                        cluster.addTestCall(new GenericField(field, clazz));
                    }
                }
            }
        }

        PutStaticMethodCollector collector = new PutStaticMethodCollector(Properties.TARGET_CLASS,
                staticFields);

        Set<MethodIdentifier> methodIdentifiers = collector.collectMethods();

        for (MethodIdentifier methodId : methodIdentifiers) {

            Class<?> clazz = getClass(methodId.getClassName());
            if (clazz == null)
                continue;

            if (!canUse(clazz))
                continue;

            Method method = getMethod(clazz, methodId.getMethodName(), methodId.getDesc());

            if (method == null)
                continue;

            GenericMethod genericMethod = new GenericMethod(method, clazz);

            cluster.addTestCall(genericMethod);

        }
    }

    logger.info("Finished analyzing target class");
}