Example usage for java.lang.reflect Modifier isAbstract

List of usage examples for java.lang.reflect Modifier isAbstract

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isAbstract.

Prototype

public static boolean isAbstract(int mod) 

Source Link

Document

Return true if the integer argument includes the abstract modifier, false otherwise.

Usage

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

/**
 * All public methods defined directly in the SUT should be covered
 * /*from   ww w.j ava  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");
}

From source file:org.mrgeo.mapalgebra.MapAlgebraParser.java

private void init() {
    OpImageRegistrar.registerMrGeoOps();

    // include any computationally expensive operations in the cached ops list.
    // This will cause the tiles to be cached. It is also a good idea to add
    // operations that read from multiple sources to the cached list.
    cachedOps.add("slope");

    parser = ParserAdapterFactory.createParserAdapter();
    parser.initialize();//from  w w w.j ava  2s  .  c  om

    // register mapops
    Reflections reflections = new Reflections("org.mrgeo");

    Set<Class<? extends MapOp>> subTypes = reflections.getSubTypesOf(MapOp.class);

    log.debug("Registering MapOps:");
    for (Class<? extends MapOp> clazz : subTypes) {
        try {
            if (!Modifier.isAbstract(clazz.getModifiers())) {
                registerFunctions(clazz);
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    for (String n : mapOps.keySet()) {
        parser.addFunction(n);
    }

    _loadFactoryFunctions();

    parser.afterFunctionsLoaded();
}

From source file:org.gvnix.addon.datatables.addon.DatatablesMetadataProvider.java

/**
 * @see DynamicFinderServicesImpl#getConcreteJavaType
 *//*  w w  w  . j av a  2 s.c o  m*/
private JavaType getConcreteJavaType(final MemberDetails memberDetails) {
    Validate.notNull(memberDetails, "Member details required");
    JavaType javaType = null;
    for (final MemberHoldingTypeDetails memberHoldingTypeDetails : memberDetails.getDetails()) {
        if (Modifier.isAbstract(memberHoldingTypeDetails.getModifier())) {
            continue;
        }
        javaType = memberHoldingTypeDetails.getName();
    }
    return javaType;
}

From source file:com.bstek.dorado.data.JsonUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object internalToJavaCollection(ArrayNode arrayNode, AggregationDataType dataType,
        Class<Collection<?>> targetType, boolean proxy, JsonConvertContext context) throws Exception {
    Class<Collection> creationType = null;
    if (dataType != null) {
        creationType = (Class<Collection>) dataType.getCreationType();
    }/*from  ww w .j av  a2 s .  com*/

    boolean shouldConvertToArray = false;
    Collection collection = null;
    if (creationType != null) {
        if (targetType != null && !targetType.isAssignableFrom(creationType)) {
            throw new IllegalArgumentException("Java type mismatch. expect [" + targetType + "].");
        }

        if (!Collection.class.isAssignableFrom(creationType)) {
            if (creationType.isArray()) {
                shouldConvertToArray = true;
            } else {
                throw new IllegalArgumentException(
                        "Java type mismatch. expect [java.util.Collection] or [Array].");
            }
        } else {
            if (!Modifier.isAbstract(creationType.getModifiers())) {
                collection = creationType.newInstance();
            }
        }
    } else if (targetType != null) {
        if (targetType.isArray()) {
            shouldConvertToArray = true;
        } else if (!Modifier.isAbstract(targetType.getModifiers())) {
            collection = targetType.newInstance();
        } else if (Set.class.isAssignableFrom(targetType)) {
            collection = new HashSet<Object>();
        }
    }

    if (collection == null) {
        collection = new ArrayList<Object>();
    }

    boolean isFirstElement = true;
    DataType elementDataType = ((dataType != null) ? dataType.getElementDataType() : null);
    Iterator<JsonNode> it = arrayNode.iterator();
    while (it.hasNext()) {
        JsonNode jsonNode = it.next();
        if (jsonNode instanceof ObjectNode) {
            ObjectNode objectNode = (ObjectNode) jsonNode;
            if (isFirstElement && elementDataType == null) {
                String dataTypeName = JsonUtils.getString(objectNode, DATATYPE_PROPERTY);
                if (StringUtils.isNotEmpty(dataTypeName)) {
                    elementDataType = getDataType(dataTypeName, context);
                }
            }
            collection.add(
                    internalToJavaEntity(objectNode, (EntityDataType) elementDataType, null, proxy, context));
        } else if (jsonNode instanceof ValueNode) {
            collection.add(toJavaValue(((ValueNode) jsonNode), elementDataType, context));
        } else {
            throw new IllegalArgumentException("Value type mismatch. expect [JSON Value].");
        }
        isFirstElement = false;
    }

    if (context != null && context.getEntityListCollection() != null) {
        context.getEntityListCollection().add(collection);
    }

    if (shouldConvertToArray) {
        return collection.toArray();
    } else {
        if (dataType != null) {
            collection = EntityUtils.toEntity(collection, dataType);
        }
        return collection;
    }
}

From source file:com.clarkparsia.empire.annotation.RdfGenerator.java

@SuppressWarnings("unchecked")
private static <T> Class<T> determineClass(Class<T> theOrigClass, T theObj, DataSource theSource,
        boolean instanceClass) throws InvalidRdfException, DataSourceException {
    Class aResult = theOrigClass;
    final SupportsRdfId aTmpSupportsRdfId = asSupportsRdfId(theObj);

    //      ExtGraph aGraph = new ExtGraph(DataSourceUtil.describe(theSource, theObj));

    // ======================================== start speedup PATCH ================================================== 
    // get class from uri without quering db

    //      final Collection<Value> aTypes = DataSourceUtil.getValues(theSource, EmpireUtil.asResource(EmpireUtil.asSupportsRdfId(theObj)), RDF.TYPE);

    String rdfId = EmpireUtil.asSupportsRdfId(theObj).getRdfId().toString();
    final Collection<Value> aTypes = Collections
            .singletonList(new URIImpl(StringUtils.substringBeforeLast(rdfId, ":")));
    // ======================================== end speedup PATCH ========================================

    // right now, our best match is the original class (we will refine later)

    //      final Resource aTmpRes = EmpireUtil.asResource(aTmpSupportsRdfId);

    // iterate for all rdf:type triples in the data
    // There may be multiple rdf:type triples, which can then translate onto multiple candidate Java classes
    // some of the Java classes may belong to the same class hierarchy, whereas others can have no common
    // super class (other than java.lang.Object)
    for (Value aValue : aTypes) {
        if (!(aValue instanceof URI)) {
            // there is no URI in the object position of rdf:type
            // ignore that data
            continue;
        }// w w w.ja va  2s.c  o m

        URI aType = (URI) aValue;

        for (Class aCandidateClass : TYPE_TO_CLASS.get(aType)) {
            if (aCandidateClass.equals(aResult)) {
                // it is mapped to the same Java class, that we have; ignore
                continue;
            }

            // at this point we found an rdf:type triple that resolves to a different Java class than we have
            // we are only going to accept this candidate class if it is a subclass of the current Java class
            // (doing otherwise, may cause class cast exceptions)

            if (aResult.isAssignableFrom(aCandidateClass)) {
                aResult = aCandidateClass;
            }
        }
    }

    try {
        if (instanceClass) {
            if (aResult.isInterface() || Modifier.isAbstract(aResult.getModifiers())
                    || !EmpireGenerated.class.isAssignableFrom(aResult)) {
                aResult = com.clarkparsia.empire.codegen.InstanceGenerator.generateInstanceClass(aResult);
            }
        }
    } catch (Exception e) {
        throw new InvalidRdfException("Cannot generate a class for a bean", e);
    }

    return aResult;
}

From source file:org.apache.openjpa.persistence.jdbc.AnnotationPersistenceMappingParser.java

@Override
protected void parseClassMappingAnnotations(ClassMetaData meta) {
    ClassMapping cm = (ClassMapping) meta;
    Class<?> cls = cm.getDescribedType();

    MappingTag tag;/*  w  ww  .  j  a va  2 s . c  o  m*/
    for (Annotation anno : cls.getDeclaredAnnotations()) {
        tag = _tags.get(anno.annotationType());
        if (tag == null) {
            handleUnknownClassMappingAnnotation(cm, anno);
            continue;
        }

        switch (tag) {
        case ASSOC_OVERRIDE:
            parseAssociationOverrides(cm, (AssociationOverride) anno);
            break;
        case ASSOC_OVERRIDES:
            parseAssociationOverrides(cm, ((AssociationOverrides) anno).value());
            break;
        case ATTR_OVERRIDE:
            parseAttributeOverrides(cm, (AttributeOverride) anno);
            break;
        case ATTR_OVERRIDES:
            parseAttributeOverrides(cm, ((AttributeOverrides) anno).value());
            break;
        case DISCRIM_COL:
            parseDiscriminatorColumn(cm, (DiscriminatorColumn) anno);
            break;
        case DISCRIM_VAL:
            cm.getDiscriminator().getMappingInfo().setValue(((DiscriminatorValue) anno).value());
            if (Modifier.isAbstract(cm.getDescribedType().getModifiers()) && getLog().isInfoEnabled()) {
                getLog().info(_loc.get("discriminator-on-abstract-class", cm.getDescribedType().getName()));
            }
            break;
        case INHERITANCE:
            parseInheritance(cm, (Inheritance) anno);
            break;
        case PK_JOIN_COL:
            parsePrimaryKeyJoinColumns(cm, (PrimaryKeyJoinColumn) anno);
            break;
        case PK_JOIN_COLS:
            parsePrimaryKeyJoinColumns(cm, ((PrimaryKeyJoinColumns) anno).value());
            break;
        case SECONDARY_TABLE:
            parseSecondaryTables(cm, (SecondaryTable) anno);
            break;
        case SECONDARY_TABLES:
            parseSecondaryTables(cm, ((SecondaryTables) anno).value());
            break;
        case SQL_RESULT_SET_MAPPING:
            parseSQLResultSetMappings(cm, (SqlResultSetMapping) anno);
            break;
        case SQL_RESULT_SET_MAPPINGS:
            parseSQLResultSetMappings(cm, ((SqlResultSetMappings) anno).value());
            break;
        case TABLE:
            parseTable(cm, (Table) anno);
            break;
        case TABLE_GEN:
            parseTableGenerator(cls, (TableGenerator) anno);
            break;
        case DATASTORE_ID_COL:
            parseDataStoreIdColumn(cm, (DataStoreIdColumn) anno);
            break;
        case DISCRIM_STRAT:
            cm.getDiscriminator().getMappingInfo().setStrategy(((DiscriminatorStrategy) anno).value());
            break;
        case FK:
            parseForeignKey(cm.getMappingInfo(), (ForeignKey) anno);
            break;
        case MAPPING_OVERRIDE:
            parseMappingOverrides(cm, (MappingOverride) anno);
            break;
        case MAPPING_OVERRIDES:
            parseMappingOverrides(cm, ((MappingOverrides) anno).value());
            break;
        case STRAT:
            cm.getMappingInfo().setStrategy(((Strategy) anno).value());
            break;
        case SUBCLASS_FETCH_MODE:
            cm.setSubclassFetchMode(toEagerFetchModeConstant(((SubclassFetchMode) anno).value()));
            break;
        case VERSION_COL:
            parseVersionColumns(cm, (VersionColumn) anno);
            break;
        case VERSION_COLS:
            parseVersionColumns(cm, ((VersionColumns) anno).value());
            break;
        case VERSION_STRAT:
            cm.getVersion().getMappingInfo().setStrategy(((VersionStrategy) anno).value());
            break;
        case X_MAPPING_OVERRIDE:
            parseMappingOverrides(cm, (XMappingOverride) anno);
            break;
        case X_MAPPING_OVERRIDES:
            parseMappingOverrides(cm, ((XMappingOverrides) anno).value());
            break;
        case X_TABLE:
        case X_SECONDARY_TABLE:
        case X_SECONDARY_TABLES:
            // no break; not supported yet
        case STOREDPROCEDURE_QUERIES:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedStoredProcedureQueries(_cls, ((NamedStoredProcedureQueries) anno).value());
            break;
        case STOREDPROCEDURE_QUERY:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedStoredProcedureQueries(_cls, ((NamedStoredProcedureQuery) anno));
            break;
        default:
            throw new UnsupportedException(_loc.get("unsupported", cm, anno));
        }
    }
}

From source file:org.apache.openjpa.kernel.StateManagerImpl.java

public void initialize(Class cls, PCState state) {
    // check to see if our current object id instance is the
    // correct id type for the specified class; this is for cases
    // when we have an application id hierarchy and we had set the
    // metadata to a superclass id -- the subclass' id may be a
    // different class, so we need to reset it
    if (_meta.getDescribedType() != cls) {
        ClassMetaData sub = _meta.getRepository().getMetaData(cls, _broker.getClassLoader(), true);
        if (_oid != null) {
            if (_meta.getIdentityType() == ClassMetaData.ID_DATASTORE)
                _oid = _broker.getStoreManager().copyDataStoreId(_oid, sub);
            else if (_meta.isOpenJPAIdentity())
                _oid = ApplicationIds.copy(_oid, sub);
            else if (sub.getObjectIdType() != _meta.getObjectIdType()) {
                Object[] pkFields = ApplicationIds.toPKValues(_oid, _meta);
                _oid = ApplicationIds.fromPKValues(pkFields, sub);
            }/*from ww  w. ja  va 2s . c  om*/
        }
        _meta = sub;
    }

    PersistenceCapable inst = PCRegistry.newInstance(cls, this, _oid, true);
    if (inst == null) {
        // the instance was null: check to see if the instance is
        // abstract (as can sometimes be the case when the
        // class discriminator strategy is not configured correctly)
        if (Modifier.isAbstract(cls.getModifiers()))
            throw new UserException(_loc.get("instantiate-abstract", cls.getName(), _oid));
        throw new InternalException();
    }

    initialize(inst, state);
}

From source file:org.deeplearning4j.nn.conf.NeuralNetConfiguration.java

private static synchronized void registerSubtypes(ObjectMapper mapper) {
    //Register concrete subtypes for JSON serialization

    List<Class<?>> classes = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class,
            IActivation.class, Layer.class, GraphVertex.class, ReconstructionDistribution.class);
    List<String> classNames = new ArrayList<>(6);
    for (Class<?> c : classes)
        classNames.add(c.getName());/* w  w w .  j  a  v a 2  s  .  c om*/

    // First: scan the classpath and find all instances of the 'baseClasses' classes
    if (subtypesClassCache == null) {

        //Check system property:
        String prop = System.getProperty(CUSTOM_FUNCTIONALITY);
        if (prop != null && !Boolean.parseBoolean(prop)) {

            subtypesClassCache = Collections.emptySet();
        } else {

            List<Class<?>> interfaces = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class,
                    IActivation.class, ReconstructionDistribution.class);
            List<Class<?>> classesList = Arrays.<Class<?>>asList(Layer.class, GraphVertex.class);

            Collection<URL> urls = ClasspathHelper.forClassLoader();
            List<URL> scanUrls = new ArrayList<>();
            for (URL u : urls) {
                String path = u.getPath();
                if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs
                    scanUrls.add(u);
                }
            }

            Reflections reflections = new Reflections(
                    new ConfigurationBuilder().filterInputsBy(new FilterBuilder().exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc
                            //Exclude the following: the assumption here is that no custom functionality will ever be present
                            // under these package name prefixes. These are all common dependencies for DL4J
                            .exclude("^org.nd4j.*").exclude("^org.datavec.*").exclude("^org.bytedeco.*") //JavaCPP
                            .exclude("^com.fasterxml.*")//Jackson
                            .exclude("^org.apache.*") //Apache commons, Spark, log4j etc
                            .exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*")
                            .exclude("^org.joda.*").exclude("^org.slf4j.*").exclude("^com.google.*")
                            .exclude("^org.reflections.*").exclude("^ch.qos.*") //Logback
                    ).addUrls(scanUrls).setScanners(new DL4JSubTypesScanner(interfaces, classesList)));
            org.reflections.Store store = reflections.getStore();

            Iterable<String> subtypesByName = store.getAll(DL4JSubTypesScanner.class.getSimpleName(),
                    classNames);

            Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName));
            subtypesClassCache = new HashSet<>();
            for (Class<?> c : subtypeClasses) {
                if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
                    //log.info("Skipping abstract/interface: {}",c);
                    continue;
                }
                subtypesClassCache.add(c);
            }
        }
    }

    //Second: get all currently registered subtypes for this mapper
    Set<Class<?>> registeredSubtypes = new HashSet<>();
    for (Class<?> c : classes) {
        AnnotatedClass ac = AnnotatedClass.construct(c,
                mapper.getSerializationConfig().getAnnotationIntrospector(), null);
        Collection<NamedType> types = mapper.getSubtypeResolver().collectAndResolveSubtypes(ac,
                mapper.getSerializationConfig(), mapper.getSerializationConfig().getAnnotationIntrospector());
        for (NamedType nt : types) {
            registeredSubtypes.add(nt.getType());
        }
    }

    //Third: register all _concrete_ subtypes that are not already registered
    List<NamedType> toRegister = new ArrayList<>();
    for (Class<?> c : subtypesClassCache) {
        //Check if it's concrete or abstract...
        if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
            //log.info("Skipping abstract/interface: {}",c);
            continue;
        }

        if (!registeredSubtypes.contains(c)) {
            String name;
            if (ClassUtils.isInnerClass(c)) {
                Class<?> c2 = c.getDeclaringClass();
                name = c2.getSimpleName() + "$" + c.getSimpleName();
            } else {
                name = c.getSimpleName();
            }
            toRegister.add(new NamedType(c, name));
            if (log.isDebugEnabled()) {
                for (Class<?> baseClass : classes) {
                    if (baseClass.isAssignableFrom(c)) {
                        log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(),
                                baseClass.getName());
                        break;
                    }
                }
            }
        }
    }

    mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()]));
}

From source file:de.codesourcery.springmass.springmass.SimulationParamsBuilder.java

private boolean isPartOfPublicInterface(Method m) {
    final int mods = m.getModifiers();
    if (Modifier.isStatic(mods) || Modifier.isAbstract(mods) || Modifier.isNative(mods)
            || !Modifier.isPublic(mods)) {
        return false;
    }//from w w w.  j  av a2s.  com
    return true;
}

From source file:org.gridgain.grid.util.json.GridJsonDeserializer.java

/**
 * Retrieves {@link JSONArray} class for deserialization.
 *
 * @param arr Array for which retrieve class.
 * @param dfltCls Default class./*ww w.  java 2 s .c  o  m*/
 * @return Class of the passed array.
 * @throws GridException Thrown if any error occurs while deserialization.
 */
private static Class getArrayClass(JSONArray arr, @Nullable Class dfltCls) throws GridException {
    assert arr != null;

    Class cls = null;

    if (arr.size() > 0) {
        boolean isFound = false;

        for (Object elem : arr)
            if (elem instanceof JSONObject) {
                JSONObject obj = (JSONObject) elem;

                if (obj.containsKey(AT_CLASS))
                    if (!isFound) {
                        cls = loadClass(obj, AT_CLASS);

                        isFound = true;
                    } else
                        throw new GridException("JSON array can contain only one element with attribute "
                                + AT_CLASS + ": " + arr);
            }
    }

    if (cls == null)
        if (dfltCls != null)
            cls = dfltCls;
        else
            cls = getDefaultClass(arr);

    assert cls != null;

    if ((cls.isInterface() || Modifier.isAbstract(cls.getModifiers())) && Iterable.class.isAssignableFrom(cls))
        if (Set.class.isAssignableFrom(cls))
            cls = HashSet.class;
        else if (Queue.class.isAssignableFrom(cls))
            cls = LinkedList.class;
        else
            cls = ArrayList.class;

    return cls;
}