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:objenome.util.bytecode.SgUtils.java

/**
 * Checks if the modifiers are valid for a method. If any of the modifiers
 * is not valid an <code>IllegalArgumentException</code> is thrown.
 * //from  w  w  w .  ja v a  2 s .  c om
 * @param modifiers
 *            Modifiers.
 */
// CHECKSTYLE:OFF Cyclomatic complexity is OK
public static void checkMethodModifiers(int modifiers) {

    // Base check
    checkModifiers(METHOD, modifiers);

    // Check overlapping modifiers
    if (Modifier.isPrivate(modifiers)) {
        if (Modifier.isProtected(modifiers) || Modifier.isPublic(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ACCESS_MODIFIER_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }
    if (Modifier.isProtected(modifiers)) {
        if (Modifier.isPrivate(modifiers) || Modifier.isPublic(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ACCESS_MODIFIER_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }
    if (Modifier.isPublic(modifiers)) {
        if (Modifier.isPrivate(modifiers) || Modifier.isProtected(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ACCESS_MODIFIER_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }

    // Check illegal abstract modifiers
    if (Modifier.isAbstract(modifiers)) {
        if (Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)
                || Modifier.isNative(modifiers) || Modifier.isStrict(modifiers)
                || Modifier.isSynchronized(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ILLEGAL_ABSTRACT_MODIFIERS_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }

    // Check native and strictfp
    if (Modifier.isNative(modifiers) && Modifier.isStrict(modifiers)) {
        throw new IllegalArgumentException(
                METHOD_NATIVE_STRICTFP_ERROR + " [" + Modifier.toString(modifiers) + ']');
    }

}

From source file:org.jgentleframework.utils.control.Delegator.java

/**
 * utility code to find the one suitable method in the passed in interface.
 * //from   ww w .  j a v  a  2  s.co  m
 * @param TheInterface
 *            the the interface
 * @return the method
 */
protected static Method findMethod(Class TheInterface) {

    if (!TheInterface.isInterface())
        throw new IllegalArgumentException("DelegateTemplate must be constructed with an interface");
    Method[] methods = TheInterface.getMethods();
    Method ret = null;
    for (int i = 0; i < methods.length; i++) {
        Method test = methods[i];
        if (Modifier.isAbstract(test.getModifiers())) {
            if (ret != null)
                throw new IllegalArgumentException("DelegateTemplate must be constructed "
                        + " with an interface implementing only one method!");
            ret = test;
        }
    }
    if (ret == null)
        throw new IllegalArgumentException(
                "DelegateTemplate must be constructed " + " with an interface implementing exactly method!");
    return (ret);
}

From source file:org.mule.util.scan.ClasspathScanner.java

protected <T> void addClassToSet(Class<T> c, Set<Class<T>> set, int flags) {
    if (c != null) {
        synchronized (set) {
            if (c.isInterface()) {
                if (hasFlag(flags, INCLUDE_INTERFACE)) {
                    set.add(c);//from  w w w. j  a  va  2  s .c  o m
                }
            } else if (Modifier.isAbstract(c.getModifiers())) {
                if (hasFlag(flags, INCLUDE_ABSTRACT)) {
                    set.add(c);
                }
            } else {
                set.add(c);
            }
        }
    }
}

From source file:org.eclipse.buildship.docs.source.SourceMetaDataVisitor.java

private int extractModifiers(GroovySourceAST t, AbstractLanguageElement metaData) {
    final int modifiers = extractModifiers(t);
    metaData.setAbstract(Modifier.isAbstract(modifiers));
    if (groovy) {
        metaData.setPublic(!Modifier.isProtected(modifiers) && !Modifier.isPrivate(modifiers));
    } else {/*from   w  w  w .j  ava 2  s. c om*/
        metaData.setPublic(Modifier.isPublic(modifiers) || (metaData instanceof MethodMetaData
                && ((MethodMetaData) metaData).getOwnerClass().isInterface()));
    }
    return modifiers;
}

From source file:org.syncope.core.rest.controller.ReportController.java

@PreAuthorize("hasRole('REPORT_LIST')")
@RequestMapping(method = RequestMethod.GET, value = "/reportletClasses")
public ModelAndView getReportletClasses() {
    CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();

    Set<String> reportletClasses = new HashSet<String>();
    try {/*  ww  w. j  a v a2s  .  c om*/
        for (Resource resource : resResolver.getResources("classpath*:**/*.class")) {

            ClassMetadata metadata = cachingMetadataReaderFactory.getMetadataReader(resource)
                    .getClassMetadata();
            if (ArrayUtils.contains(metadata.getInterfaceNames(), Reportlet.class.getName())
                    || AbstractReportlet.class.getName().equals(metadata.getSuperClassName())) {

                try {
                    Class jobClass = Class.forName(metadata.getClassName());
                    if (!Modifier.isAbstract(jobClass.getModifiers())) {

                        reportletClasses.add(jobClass.getName());
                    }
                } catch (ClassNotFoundException e) {
                    LOG.error("Could not load class {}", metadata.getClassName(), e);
                }
            }
        }
    } catch (IOException e) {
        LOG.error("While searching for class implementing {}", Reportlet.class.getName(), e);
    }

    ModelAndView result = new ModelAndView();
    result.addObject(reportletClasses);
    return result;
}

From source file:org.apache.struts2.config.ClasspathConfigurationProvider.java

/**
 * Scan a list of packages for Action classes.
 *
 * This method loads classes that implement the Action interface
 * or have a class name that ends with the letters "Action".
 *
 * @param pkgs A list of packages to load
 * @see #processActionClass//from   w w  w.j  a  v  a2  s  .c  o  m
 */
protected void loadPackages(String[] pkgs) {

    ResolverUtil<Class> resolver = new ResolverUtil<Class>();
    resolver.find(new Test() {
        // Match Action implementations and classes ending with "Action"
        public boolean matches(Class type) {
            // TODO: should also find annotated classes
            return (Action.class.isAssignableFrom(type) || type.getSimpleName().endsWith("Action"));
        }

    }, pkgs);

    Set<? extends Class<? extends Class>> actionClasses = resolver.getClasses();
    for (Object obj : actionClasses) {
        Class cls = (Class) obj;
        if (!Modifier.isAbstract(cls.getModifiers())) {
            processActionClass(cls, pkgs);
        }
    }

    for (String key : loadedPackageConfigs.keySet()) {
        configuration.addPackageConfig(key, loadedPackageConfigs.get(key));
    }
}

From source file:org.zanata.seam.SeamAutowire.java

/**
 * Registers an implementation to use for beans. This method is
 * provided for beans which are injected by interface rather than name.
 *
 * @param cls/*from  www  .  ja v  a 2 s .  c o m*/
 *            The class to register.
 */
public SeamAutowire useImpl(Class<?> cls) {
    if (Modifier.isAbstract(cls.getModifiers())) {
        throw new AutowireException("Class " + cls.getName() + " is abstract.");
    }
    this.registerInterfaces(cls);

    return this;
}

From source file:org.roda.core.migration.MigrationManager.java

private Map<String, Integer> getModelClassesVersionsFromCode(final boolean avoidClassesByNamePrefix,
        final String avoidByNamePrefix) {
    Map<String, Integer> ret = new HashMap<>();
    Reflections reflections = new Reflections("org.roda.core.data.v2");
    Set<Class<? extends IsModelObject>> modelClasses = reflections.getSubTypesOf(IsModelObject.class);
    for (Class<? extends IsModelObject> clazz : modelClasses) {
        if (Modifier.isAbstract(clazz.getModifiers())
                || (avoidClassesByNamePrefix && clazz.getSimpleName().startsWith(avoidByNamePrefix))) {
            continue;
        }/*from w w w.j  av a 2 s. c o m*/

        try {
            ret.put(clazz.getName(), clazz.newInstance().getClassVersion());
        } catch (InstantiationException | IllegalAccessException e) {
            LOGGER.error("Unable to determine class '{}' model version", clazz.getName(), e);
        }
    }
    return ret;
}

From source file:org.structr.schema.SchemaService.java

public static boolean reloadSchema(final ErrorBuffer errorBuffer, final String initiatedBySessionId) {

    final ConfigurationProvider config = StructrApp.getConfiguration();
    final App app = StructrApp.getInstance();
    boolean success = true;

    // compiling must only be done once
    if (compiling.compareAndSet(false, true)) {

        FlushCachesCommand.flushAll();/*from w  w  w .  j  av a 2s .  c o m*/

        final long t0 = System.currentTimeMillis();

        try {

            final Map<String, Map<String, PropertyKey>> removedClasses = new HashMap<>(
                    config.getTypeAndPropertyMapping());
            final Map<String, GraphQLType> graphQLTypes = new LinkedHashMap<>();
            final Map<String, SchemaNode> schemaNodes = new LinkedHashMap<>();
            final NodeExtender nodeExtender = new NodeExtender(initiatedBySessionId);
            final Set<String> dynamicViews = new LinkedHashSet<>();

            try (final Tx tx = app.tx()) {

                // collect auto-generated schema nodes
                SchemaService.ensureBuiltinTypesExist(app);

                // collect list of schema nodes
                app.nodeQuery(SchemaNode.class).getAsList().stream().forEach(n -> {
                    schemaNodes.put(n.getName(), n);
                });

                // check licenses prior to source code generation
                for (final SchemaNode schemaInfo : schemaNodes.values()) {
                    blacklist.addAll(SchemaHelper.getUnlicensedTypes(schemaInfo));
                }

                // add schema nodes from database
                for (final SchemaNode schemaInfo : schemaNodes.values()) {

                    final String name = schemaInfo.getName();
                    if (blacklist.contains(name)) {

                        continue;
                    }

                    schemaInfo.handleMigration();

                    final String sourceCode = SchemaHelper.getSource(schemaInfo, schemaNodes, blacklist,
                            errorBuffer);
                    if (sourceCode != null) {

                        final String className = schemaInfo.getClassName();

                        // only load dynamic node if there were no errors while generating
                        // the source code (missing modules etc.)
                        nodeExtender.addClass(className, sourceCode);
                        dynamicViews.addAll(schemaInfo.getDynamicViews());

                        // initialize GraphQL engine as well
                        schemaInfo.initializeGraphQL(schemaNodes, graphQLTypes, blacklist);
                    }
                }

                // collect relationship classes
                for (final SchemaRelationshipNode schemaRelationship : app
                        .nodeQuery(SchemaRelationshipNode.class).getAsList()) {

                    final String sourceType = schemaRelationship.getSchemaNodeSourceType();
                    final String targetType = schemaRelationship.getSchemaNodeTargetType();

                    if (!blacklist.contains(sourceType) && !blacklist.contains(targetType)) {

                        nodeExtender.addClass(schemaRelationship.getClassName(),
                                schemaRelationship.getSource(schemaNodes, errorBuffer));
                        dynamicViews.addAll(schemaRelationship.getDynamicViews());

                        // initialize GraphQL engine as well
                        schemaRelationship.initializeGraphQL(graphQLTypes);
                    }
                }

                // this is a very critical section :)
                synchronized (SchemaService.class) {

                    // clear propagating relationship cache
                    SchemaRelationshipNode.clearPropagatingRelationshipTypes();

                    // compile all classes at once and register
                    final Map<String, Class> newTypes = nodeExtender.compile(errorBuffer);

                    for (final Class newType : newTypes.values()) {

                        // instantiate classes to execute static initializer of helpers
                        try {

                            // do full reload
                            config.registerEntityType(newType);
                            newType.newInstance();

                        } catch (final Throwable t) {

                            // abstract classes and interfaces will throw errors here
                            if (newType.isInterface() || Modifier.isAbstract(newType.getModifiers())) {
                                // ignore
                            } else {

                                // everything else is a severe problem and should be not only reported but also
                                // make the schema compilation fail (otherwise bad things will happen later)
                                errorBuffer.add(new InstantiationErrorToken(newType.getName(), t));
                                logger.error("Unable to instantiate dynamic entity {}", newType.getName(), t);
                            }
                        }
                    }

                    // calculate difference between previous and new classes
                    removedClasses.keySet()
                            .removeAll(StructrApp.getConfiguration().getTypeAndPropertyMapping().keySet());
                }

                // create properties and views etc.
                for (final SchemaNode schemaNode : schemaNodes.values()) {
                    schemaNode.createBuiltInSchemaEntities(errorBuffer);
                }

                success = !errorBuffer.hasError();

                if (success) {

                    // prevent inheritance map from leaking
                    SearchCommand.clearInheritanceMap();
                    AccessPathCache.invalidate();

                    // clear relationship instance cache
                    AbstractNode.clearRelationshipTemplateInstanceCache();

                    // clear permission cache
                    AbstractNode.clearCaches();

                    // inject views in configuration provider
                    config.registerDynamicViews(dynamicViews);

                    if (Services.calculateHierarchy() || !Services.isTesting()) {

                        calculateHierarchy(schemaNodes);
                    }

                    if (Services.updateIndexConfiguration() || !Services.isTesting()) {

                        updateIndexConfiguration(removedClasses);
                    }

                    tx.success();

                    final GraphQLObjectType.Builder queryTypeBuilder = GraphQLObjectType.newObject();
                    final Map<String, GraphQLInputObjectType> selectionTypes = new LinkedHashMap<>();
                    final Set<String> existingQueryTypeNames = new LinkedHashSet<>();

                    // register types in "Query" type
                    for (final Entry<String, GraphQLType> entry : graphQLTypes.entrySet()) {

                        final String className = entry.getKey();
                        final GraphQLType type = entry.getValue();

                        try {

                            // register type in query type
                            queryTypeBuilder.field(GraphQLFieldDefinition.newFieldDefinition().name(className)
                                    .type(new GraphQLList(type))
                                    .argument(GraphQLArgument.newArgument().name("id")
                                            .type(Scalars.GraphQLString).build())
                                    .argument(GraphQLArgument.newArgument().name("type")
                                            .type(Scalars.GraphQLString).build())
                                    .argument(GraphQLArgument.newArgument().name("name")
                                            .type(Scalars.GraphQLString).build())
                                    .argument(GraphQLArgument.newArgument().name("_page")
                                            .type(Scalars.GraphQLInt).build())
                                    .argument(GraphQLArgument.newArgument().name("_pageSize")
                                            .type(Scalars.GraphQLInt).build())
                                    .argument(GraphQLArgument.newArgument().name("_sort")
                                            .type(Scalars.GraphQLString).build())
                                    .argument(GraphQLArgument.newArgument().name("_desc")
                                            .type(Scalars.GraphQLBoolean).build())
                                    .argument(SchemaHelper.getGraphQLQueryArgumentsForType(schemaNodes,
                                            selectionTypes, existingQueryTypeNames, className)));

                        } catch (Throwable t) {
                            logger.warn("Unable to add GraphQL type {}: {}", className, t.getMessage());
                        }
                    }

                    // exchange graphQL schema after successful build
                    synchronized (SchemaService.class) {

                        try {

                            graphQLSchema = GraphQLSchema.newSchema()
                                    .query(queryTypeBuilder.name("Query").build())
                                    .build(new LinkedHashSet<>(graphQLTypes.values()));

                        } catch (Throwable t) {
                            logger.warn("Unable to build GraphQL schema: {}", t.getMessage());
                        }
                    }
                }

            } catch (FrameworkException fex) {

                FlushCachesCommand.flushAll();

                logger.error("Unable to compile dynamic schema: {}", fex.getMessage());
                success = false;

                errorBuffer.getErrorTokens().addAll(fex.getErrorBuffer().getErrorTokens());

            } catch (Throwable t) {

                FlushCachesCommand.flushAll();

                t.printStackTrace();

                logger.error("Unable to compile dynamic schema: {}", t.getMessage());
                success = false;
            }

            if (!success) {

                FlushCachesCommand.flushAll();

                logger.error("Errors encountered during compilation:");
                for (ErrorToken token : errorBuffer.getErrorTokens()) {
                    logger.error(" - {}", token.toString());
                }

                if (Settings.SchemAutoMigration.getValue()) {

                    logger.info("Attempting auto-migration...");

                    // handle migration in separate transaction
                    try (final Tx tx = app.tx()) {

                        // try to handle certain errors automatically
                        handleAutomaticMigration(errorBuffer);

                        tx.success();

                    } catch (FrameworkException fex) {

                    }

                } else {

                    logger.error(
                            "Unable to compile dynamic schema, and automatic migration is not enabled. Please set application.schema.automigration = true in structr.conf to enable modification of existing schema classes.");

                }
            }

        } finally {

            logger.info("Schema build took a total of {} ms", System.currentTimeMillis() - t0);

            // compiling done
            compiling.set(false);

        }
    }

    return success;
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Check if a class is abstract class or interface.
 * //from  w w  w.  j  a v  a  2s .  c o m
 * @param clazz
 *            the class
 * @return true if yes, false not
 */
public static boolean isAbstract(Class<?> clazz) {
    return Modifier.isAbstract(clazz.getModifiers());
}