Example usage for java.lang Class getModifiers

List of usage examples for java.lang Class getModifiers

Introduction

In this page you can find the example usage for java.lang Class getModifiers.

Prototype

@HotSpotIntrinsicCandidate
public native int getModifiers();

Source Link

Document

Returns the Java language modifiers for this class or interface, encoded in an integer.

Usage

From source file:org.apache.bval.jsr.ClassValidator.java

/**
 * {@inheritDoc} Return an instance of the specified type allowing access to provider-specific APIs. If the Bean
 * Validation provider implementation does not support the specified class, <code>ValidationException</code> is
 * thrown.//  www.ja  va  2s. c  o  m
 *
 * @param type the class of the object to be returned.
 * @return an instance of the specified class
 * @throws ValidationException if the provider does not support the call.
 */
// @Override - not allowed in 1.5 for Interface methods
public <T> T unwrap(Class<T> type) {
    // FIXME 2011-03-27 jw:
    // This code is unsecure.
    // It should allow only a fixed set of classes.
    // Can't fix this because don't know which classes this method should support.

    if (type.isAssignableFrom(getClass())) {
        @SuppressWarnings("unchecked")
        final T result = (T) this;
        return result;
    }
    if (!(type.isInterface() || Modifier.isAbstract(type.getModifiers()))) {
        return newInstance(type);
    }
    try {
        final Class<?> cls = ClassUtils.getClass(type.getName() + "Impl");
        if (type.isAssignableFrom(cls)) {
            @SuppressWarnings("unchecked")
            final Class<? extends T> implClass = (Class<? extends T>) cls;
            return newInstance(implClass);
        }
    } catch (ClassNotFoundException e) {
    }
    throw new ValidationException("Type " + type + " not supported");
}

From source file:org.evosuite.testcase.TestCodeVisitor.java

/** {@inheritDoc} */
@Override//from  w w  w  .  ja v a 2s .c o m
public void visitFieldStatement(FieldStatement statement) {
    Throwable exception = getException(statement);

    String cast_str = "";
    StringBuilder builder = new StringBuilder();

    VariableReference retval = statement.getReturnValue();
    GenericField field = statement.getField();

    if (!retval.isAssignableFrom(field.getFieldType())) {
        cast_str += "(" + getClassName(retval) + ")";
    }

    if (exception != null) {
        builder.append(getClassName(retval));
        builder.append(" ");
        builder.append(getVariableName(retval));
        builder.append(" = null;");
        builder.append(NEWLINE);
        builder.append("try {  ");
        builder.append(NEWLINE);
    } else {
        builder.append(getClassName(retval));
        builder.append(" ");
    }
    if (!field.isStatic()) {
        VariableReference source = statement.getSource();
        builder.append(getVariableName(retval));
        builder.append(" = ");
        builder.append(cast_str);
        builder.append(getVariableName(source));
        builder.append(".");
        builder.append(field.getName());
        builder.append(";");
    } else {
        builder.append(getVariableName(retval));
        builder.append(" = ");
        builder.append(cast_str);
        builder.append(getClassName(field.getField().getDeclaringClass()));
        builder.append(".");
        builder.append(field.getName());
        builder.append(";");
    }
    if (exception != null) {
        Class<?> ex = exception.getClass();
        while (!Modifier.isPublic(ex.getModifiers()))
            ex = ex.getSuperclass();
        builder.append(NEWLINE);
        builder.append("} catch(");
        builder.append(getClassName(ex));
        builder.append(" e) {}");
    }
    builder.append(NEWLINE);

    testCode += builder.toString();
    addAssertions(statement);
}

From source file:com.zyf.framework.plugin.SqlSessionFactoryBean.java

/**
 * Build a {@code SqlSessionFactory} instance.
 *
 * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
 * {@code SqlSessionFactory} instance based on an Reader.
 * Since 1.3.0, it can be specified a {@link Configuration} instance directly(without config file).
 *
 * @return SqlSessionFactory//from   w  w w .  j a  va  2  s. com
 * @throws IOException if loading the config file failed
 */
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configuration != null) {
        configuration = this.configuration;
        if (configuration.getVariables() == null) {
            configuration.setVariables(this.configurationProperties);
        } else if (this.configurationProperties != null) {
            configuration.getVariables().putAll(this.configurationProperties);
        }
    } else if (this.configLocation != null) {
        xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null,
                this.configurationProperties);
        configuration = xmlConfigBuilder.getConfiguration();
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(
                    "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
        }
        configuration = new Configuration();
        if (this.configurationProperties != null) {
            configuration.setVariables(this.configurationProperties);
        }
    }

    if (this.objectFactory != null) {
        configuration.setObjectFactory(this.objectFactory);
    }

    if (this.objectWrapperFactory != null) {
        configuration.setObjectWrapperFactory(this.objectWrapperFactory);
    }

    if (this.vfs != null) {
        configuration.setVfsImpl(this.vfs);
    }

    if (hasLength(this.typeAliasesPackage)) {
        String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        for (String packageToScan : typeAliasPackageArray) {
            configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                    typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
            }
        }
    }

    if (!isEmpty(this.typeAliases)) {
        for (Class<?> typeAlias : this.typeAliases) {
            configuration.getTypeAliasRegistry().registerAlias(typeAlias);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Registered type alias: '" + typeAlias + "'");
            }
        }
    }

    if (!isEmpty(this.plugins)) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Registered plugin: '" + plugin + "'");
            }
        }
    }

    if (hasLength(this.typeHandlersPackage)) {
        String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage,
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        for (String packageToScan : typeHandlersPackageArray) {
            configuration.getTypeHandlerRegistry().register(packageToScan);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers");
            }
        }
    }

    if (!isEmpty(this.typeHandlers)) {
        for (TypeHandler<?> typeHandler : this.typeHandlers) {

            //TODO:
            ClazzTypeScan cts = typeHandler.getClass().getAnnotation(ClazzTypeScan.class);
            if (cts == null) {
                configuration.getTypeHandlerRegistry().register(typeHandler);
            } else {
                TypeScan typescan = cts.value();
                if (typeScanMap.containsKey(typescan.name())) {
                    String scanpath = typeScanMap.get(typescan.name());

                    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
                    resolverUtil.find(new ResolverUtil.IsA(DescriptionID.class), scanpath);
                    Set<Class<? extends Class<?>>> handlerSet = resolverUtil.getClasses();
                    for (Class<?> type : handlerSet) {
                        try {
                            Constructor<?> c = typeHandler.getClass().getConstructor(Class.class);
                            c.newInstance(type);
                        } catch (NoSuchMethodException | SecurityException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }

                        if (!type.isAnonymousClass() && !type.isInterface()
                                && !Modifier.isAbstract(type.getModifiers())) {
                            configuration.getTypeHandlerRegistry().register(type, typeHandler.getClass());
                        }
                    }

                }
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Registered type handler: '" + typeHandler + "'");
            }
        }
    }

    if (this.databaseIdProvider != null) {//fix #64 set databaseId before parse mapper xmls
        try {
            configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
        } catch (SQLException e) {
            throw new NestedIOException("Failed getting a databaseId", e);
        }
    }

    if (this.cache != null) {
        configuration.addCache(this.cache);
    }

    if (xmlConfigBuilder != null) {
        try {
            xmlConfigBuilder.parse();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'");
            }
        } catch (Exception ex) {
            throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    if (this.transactionFactory == null) {
        this.transactionFactory = new SpringManagedTransactionFactory();
    }

    configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));

    if (!isEmpty(this.mapperLocations)) {
        for (Resource mapperLocation : this.mapperLocations) {
            if (mapperLocation == null) {
                continue;
            }

            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                        configuration, mapperLocation.toString(), configuration.getSqlFragments());
                xmlMapperBuilder.parse();
            } catch (Exception e) {
                throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
            } finally {
                ErrorContext.instance().reset();
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
            }
        }

        // ThinkGem ?MapperXML?
        if (mapperRefresh.isEnabled()) {
            System.out.println("mapperRefresh loading.............");
            mapperRefresh.setConfiguration(configuration);
            mapperRefresh.setMapperLocations(mapperLocations);
            mapperRefresh.run();
        }

    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
        }
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Return the concrete type for proxying.
 *//*ww  w .  jav a  2s .c o m*/
protected Class toProxyableMapType(Class type) {
    if (type.getName().endsWith(PROXY_SUFFIX))
        type = type.getSuperclass();
    else if (type.isInterface()) {
        type = toConcreteType(type, _stdMaps);
        if (type == null)
            throw new UnsupportedException(_loc.get("no-proxy-intf", type));
    } else if (Modifier.isAbstract(type.getModifiers()))
        throw new UnsupportedException(_loc.get("no-proxy-abstract", type));
    return type;
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Return the concrete type for proxying.
 *///from   ww  w  .  j a  va 2s  . c o m
protected Class toProxyableCollectionType(Class type) {
    if (type.getName().endsWith(PROXY_SUFFIX))
        type = type.getSuperclass();
    else if (type.isInterface()) {
        type = toConcreteType(type, _stdCollections);
        if (type == null)
            throw new UnsupportedException(_loc.get("no-proxy-intf", type));
    } else if (Modifier.isAbstract(type.getModifiers()))
        throw new UnsupportedException(_loc.get("no-proxy-abstract", type));
    return type;
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Create a new instance for the specified bean, using an appropriate instantiation strategy:
 * factory method, constructor autowiring, or simple instantiation.
 * @param beanName the name of the bean/*ww  w .j a v  a  2  s  .c o  m*/
 * @param mbd the bean definition for the bean
 * @param args explicit arguments to use for constructor or factory method invocation
 * @return a BeanWrapper for the new instance
 * @see #obtainFromSupplier
 * @see #instantiateUsingFactoryMethod
 * @see #autowireConstructor
 * @see #instantiateBean
 */
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // Make sure bean class is actually resolved at this point.
    Class<?> beanClass = resolveBeanClass(mbd, beanName);

    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }

    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }

    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // Shortcut when re-creating the same bean...
    boolean resolved = false;
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    if (resolved) {
        if (autowireNecessary) {
            return autowireConstructor(beanName, mbd, null, null);
        } else {
            return instantiateBean(beanName, mbd);
        }
    }

    // Need to determine the constructor...
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR
            || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    // No special handling: simply use no-arg constructor.
    return instantiateBean(beanName, mbd);
}

From source file:com.evolveum.midpoint.prism.PrismContainerValue.java

public C asContainerable() {
    PrismContainerable parent = getParent();
    if (parent == null) {
        throw new IllegalStateException(
                "Cannot represent container value without a parent as containerable; value: " + this);
    }/*from  ww w.j a v  a 2s .  co m*/

    Class<C> clazz = null;
    if (concreteType != null) {
        clazz = resolveConcreteClass(parent);
    }
    if (clazz == null) {
        clazz = parent.getCompileTimeClass();
    }
    if (clazz == null) {
        throw new SystemException("Unknown compile time class of container '" + parent.getElementName() + "'.");
    }
    if (Modifier.isAbstract(clazz.getModifiers())) {
        throw new SystemException(
                "Can't create instance of class '" + clazz.getSimpleName() + "', it's abstract.");
    }
    return asContainerableInternal(clazz);
}

From source file:com.amalto.core.metadata.ClassRepository.java

private TypeMetadata loadClass(Class clazz) {
    String typeName = getTypeName(clazz);
    if (getType(typeName) != null) { // If already defined return it.
        return getType(typeName);
    } else if (getNonInstantiableType(StringUtils.EMPTY, typeName) != null) {
        return getNonInstantiableType(StringUtils.EMPTY, typeName);
    }/*from  www .  j  a v a  2s. c  o  m*/
    entityToJavaClass.put(typeName, clazz);
    if (Map.class.isAssignableFrom(clazz)) {
        return MAP_TYPE;
    }
    if (ArrayListHolder.class.equals(clazz)) {
        typeName = typeName + listCounter++;
    }
    boolean isEntity = typeStack.isEmpty();
    ComplexTypeMetadata classType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, typeName, isEntity);
    addTypeMetadata(classType);
    typeStack.push(classType);
    String keyFieldName = ""; //$NON-NLS-1$
    if (isEntity && ObjectPOJO.class.isAssignableFrom(clazz)) {
        SimpleTypeFieldMetadata keyField = new SimpleTypeFieldMetadata(typeStack.peek(), true, false, true,
                "unique-id", //$NON-NLS-1$
                STRING, Collections.<String>emptyList(), Collections.<String>emptyList(),
                Collections.<String>emptyList(), StringUtils.EMPTY);
        keyField.setData(LINK, "PK/unique-id"); //$NON-NLS-1$
        classType.addField(keyField);
    } else if (isEntity) {
        keyFieldName = "unique-id"; //$NON-NLS-1$
    }
    // Class is abstract / interface: load sub classes
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        Iterable<Class> subClasses = getSubclasses(clazz);
        ComplexTypeMetadata superType = typeStack.peek();
        if (superType.isInstantiable()) {
            typeStack.clear();
        }
        for (Class subClass : subClasses) {
            TypeMetadata typeMetadata = loadClass(subClass);
            typeMetadata.setInstantiable(superType.isInstantiable());
            typeMetadata.addSuperType(superType);
        }
        if (superType.isInstantiable()) {
            typeStack.push(superType);
        }
    }
    // Analyze methods
    Method[] classMethods = getMethods(clazz);
    for (Method declaredMethod : classMethods) {
        if (!Modifier.isStatic(declaredMethod.getModifiers())) {
            if (isBeanMethod(declaredMethod) && isClassMethod(clazz, declaredMethod)) {
                String fieldName = getName(declaredMethod);
                if (typeStack.peek().hasField(fieldName)) {
                    continue; // TODO Avoid override of fields (like PK)
                }
                Class<?> returnType = declaredMethod.getReturnType();
                FieldMetadata newField;
                boolean isMany = false;
                boolean isKey = keyFieldName.equals(fieldName);
                if (Iterable.class.isAssignableFrom(returnType)) {
                    returnType = listItemType != null ? listItemType
                            : getListItemClass(declaredMethod, returnType);
                    listItemType = null;
                    isMany = true;
                } else if (ArrayListHolder.class.isAssignableFrom(returnType)) {
                    listItemType = getListItemClass(declaredMethod, returnType);
                    isMany = false;
                } else if (Map.class.isAssignableFrom(returnType)) {
                    isMany = true;
                } else if (returnType.isArray()) {
                    isMany = true;
                    returnType = ((Class) returnType.getComponentType());
                } else if (returnType.getName().startsWith("org.w3c.")) { //$NON-NLS-1$
                    // TODO Serialized XML to string column
                    continue;
                } else if (Class.class.equals(returnType)) {
                    continue;
                } else if (returnType.getPackage() != null
                        && returnType.getPackage().getName().startsWith("java.io")) { //$NON-NLS-1$
                    continue;
                }
                if (returnType.isPrimitive() || returnType.getName().startsWith(JAVA_LANG_PREFIX)) {
                    String fieldTypeName = returnType.getName().toLowerCase();
                    if (fieldTypeName.startsWith(JAVA_LANG_PREFIX)) {
                        fieldTypeName = StringUtils.substringAfter(fieldTypeName, JAVA_LANG_PREFIX);
                    }
                    TypeMetadata fieldType;
                    if (Types.BYTE.equals(fieldTypeName) && isMany) {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                Types.BASE64_BINARY);
                    } else {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldTypeName);
                    }
                    newField = new SimpleTypeFieldMetadata(typeStack.peek(), isKey, isMany, isKey, fieldName,
                            fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(),
                            Collections.<String>emptyList(), StringUtils.EMPTY);
                    LongString annotation = declaredMethod.getAnnotation(LongString.class);
                    if (Types.STRING.equals(fieldTypeName) && annotation != null) {
                        fieldType.setData(MetadataRepository.DATA_MAX_LENGTH,
                                String.valueOf(Integer.MAX_VALUE));
                        if (annotation.preferLongVarchar()) {
                            fieldType.setData(LongString.PREFER_LONGVARCHAR, Boolean.TRUE);
                        }
                    }
                } else {
                    ComplexTypeMetadata fieldType;
                    if (Map.class.isAssignableFrom(returnType)) {
                        fieldType = MAP_TYPE;
                    } else {
                        fieldType = (ComplexTypeMetadata) loadClass(returnType);
                    }
                    if (!isEntity || !fieldType.isInstantiable()) {
                        newField = new ContainedTypeFieldMetadata(typeStack.peek(), isMany, false, fieldName,
                                new SoftTypeRef(this, StringUtils.EMPTY, fieldType.getName(), false),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY);
                    } else {
                        newField = new ReferenceFieldMetadata(typeStack.peek(), false, isMany, false, fieldName,
                                fieldType, fieldType.getField("unique-id"), //$NON-NLS-1$
                                Collections.<FieldMetadata>emptyList(), StringUtils.EMPTY, true, false, STRING,
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY, StringUtils.EMPTY);
                    }
                }
                typeStack.peek().addField(newField);
            }
        }
    }

    typeStack.peek().addField(new SimpleTypeFieldMetadata(typeStack.peek(), false, false, false, "digest", //$NON-NLS-1$
            new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING),
            Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(),
            StringUtils.EMPTY));

    return typeStack.pop();
}

From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private EntityModel createBeanEntity(Class clazz, RegistryNodeModel registryNodeModel,
        List<RelationshipModel> relationships, Map<String, EntityModel> models) {
    if (clazz == Object.class)
        return null;

    EntityModel model = models.get(clazz.getName());
    if (model != null)
        return model;

    String name = clazz.getSimpleName().replaceAll("\\B([A-Z]+)\\B", " $1");

    EntityModel entityModel;//from  w  ww  . ja v a 2s. c o m
    if (clazz.isMemberClass()) {
        entityModel = new SubEntityModel();
        name = "Nested " + name;
        registryNodeModel = models.get(clazz.getEnclosingClass().getName());
    } else {
        entityModel = new EntityModel();
    }

    models.put(clazz.getName(), entityModel);

    entityModel.setName(name);
    entityModel.setLookup(DiffUtils.lookup(registryNodeModel.getLookup(), name));
    entityModel.setPath(registryNodeModel.getLookup());
    entityModel.setAbstractEntity(Modifier.isAbstract(clazz.getModifiers()));
    entityModel.setTypeEntity(true);
    entityModel.setReverseEngineer(true);
    entityModel.setExtendedEntity(
            createBeanEntity(clazz.getSuperclass(), registryNodeModel, relationships, models));
    entityModel.setProtocol(EntityProtocol.HTTP);
    entityModel.setParent(registryNodeModel);

    Field[] declaredFields = clazz.getDeclaredFields();
    List<FieldModel> fields = new ArrayList<FieldModel>(declaredFields.length);

    for (Field field : declaredFields) {
        analyzeField(field.getName(), field.getGenericType(), TYPE, entityModel,
                field.getAnnotation(XmlElement.class), models, relationships, fields);

        XmlElements xmlElements = field.getAnnotation(XmlElements.class);
        if (xmlElements != null) {
            XmlElement[] elements = xmlElements.value();
            List<EntityModel> options = new ArrayList<EntityModel>(elements.length);
            RegistryNodeModel parent = clazz.isMemberClass() ? registryNodeModel.getParent()
                    : registryNodeModel;
            for (XmlElement element : elements) {
                if (element.type().isAnnotationPresent(XmlAccessorType.class)) {
                    EntityModel entity = createBeanEntity(element.type(), parent, relationships, models);
                    options.add(entity);
                }
            }
            FieldModel fieldModel = fields.get(fields.size() - 1);
            fieldModel.setOptions(options);
        }
    }

    entityModel.setFields(fields);

    return entityModel;
}

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

public static Set<Class<?>> getConcreteClasses(Class<?> clazz, InheritanceTree inheritanceTree) {

    // Some special cases
    if (clazz.equals(java.util.Map.class))
        return getConcreteClassesMap();
    else if (clazz.equals(java.util.List.class))
        return getConcreteClassesList();
    else if (clazz.equals(java.util.Set.class))
        return getConcreteClassesSet();
    else if (clazz.equals(java.util.Collection.class))
        return getConcreteClassesList();
    else if (clazz.equals(java.util.Iterator.class))
        // We don't want to explicitly create iterators
        // This would only pull in java.util.Scanner, the only
        // concrete subclass
        return new LinkedHashSet<Class<?>>();
    else if (clazz.equals(java.util.ListIterator.class))
        // We don't want to explicitly create iterators
        return new LinkedHashSet<Class<?>>();
    else if (clazz.equals(java.io.Serializable.class))
        return new LinkedHashSet<Class<?>>();
    else if (clazz.equals(java.lang.Comparable.class))
        return getConcreteClassesComparable();
    else if (clazz.equals(java.util.Comparator.class))
        return new LinkedHashSet<Class<?>>();

    Set<Class<?>> actualClasses = new LinkedHashSet<Class<?>>();
    if (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())
            || clazz.equals(Enum.class)) {
        Set<String> subClasses = inheritanceTree.getSubclasses(clazz.getName());
        logger.debug("Subclasses of {}: {}", clazz.getName(), subClasses);
        Map<String, Integer> classDistance = new HashMap<String, Integer>();
        int maxDistance = -1;
        String name = clazz.getName();
        if (clazz.equals(Enum.class)) {
            name = Properties.TARGET_CLASS;
        }//  www. jav  a2s .  com
        for (String subClass : subClasses) {
            int distance = getPackageDistance(subClass, name);
            classDistance.put(subClass, distance);
            maxDistance = Math.max(distance, maxDistance);
        }
        int distance = 0;
        while (actualClasses.isEmpty() && distance <= maxDistance) {
            logger.debug(" Current distance: {}", distance);
            for (String subClass : subClasses) {
                if (classDistance.get(subClass) == distance) {
                    try {
                        Class<?> subClazz = Class.forName(subClass, false,
                                TestGenerationContext.getInstance().getClassLoaderForSUT());
                        if (!canUse(subClazz))
                            continue;
                        if (subClazz.isInterface())
                            continue;
                        if (Modifier.isAbstract(subClazz.getModifiers())) {
                            if (!hasStaticGenerator(subClazz))
                                continue;
                        }
                        Class<?> mock = MockList.getMockClass(subClazz.getCanonicalName());
                        if (mock != null) {
                            /*
                             * If we are mocking this class, then such class should not be used
                             * in the generated JUnit test cases, but rather its mock.
                             */
                            logger.debug("Adding mock {} instead of {}", mock, clazz);
                            subClazz = mock;
                        } else {

                            if (!checkIfCanUse(subClazz.getCanonicalName())) {
                                continue;
                            }
                        }

                        actualClasses.add(subClazz);

                    } catch (ClassNotFoundException e) {
                        logger.error("Problem for {}. Class not found: {}", Properties.TARGET_CLASS, subClass,
                                e);
                        logger.error("Removing class from inheritance tree");
                        inheritanceTree.removeClass(subClass);
                    }
                }
            }
            distance++;
        }
        if (hasStaticGenerator(clazz)) {
            actualClasses.add(clazz);
        }
        if (actualClasses.isEmpty()) {
            logger.info("Don't know how to instantiate abstract class {}", clazz.getName());
        }
    } else {
        actualClasses.add(clazz);
    }

    logger.debug("Subclasses of {}: {}", clazz.getName(), actualClasses);
    return actualClasses;
}