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:eu.squadd.testing.objectspopulator.RandomValuePopulator.java

public Object populateAllFields(final Class targetClass, Map exclusions)
        throws IllegalAccessException, InstantiationException {
    final Object target;
    try {//from www  . j  a v  a2  s . com
        if (isMathNumberType(targetClass)) {
            target = getMathNumberType(targetClass);
        } else {
            target = ConstructorUtils.invokeConstructor(targetClass, null);
        }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
            | InstantiationException ex) {
        System.err.println(ex.getMessage());
        return null;
    }

    //final Object target = targetClass.newInstance();
    //Get all fields present on the target class
    final Set<Field> allFields = getAllFields(targetClass, Predicates.<Field>alwaysTrue());
    if (this.stopOnMxRecusionDepth)
        this.currentRecursionDepth++;

    //Iterate through fields if recursion depth is not reached
    if (!this.stopOnMxRecusionDepth || (this.stopOnMxRecusionDepth
            && this.currentRecursionDepth <= scannerFactory.getRecursionDepth())) {
        for (final Field field : allFields) {
            try {
                // check if the field is not on exclusion list                
                if (exclusions != null && exclusions.containsValue(field.getName()))
                    continue;

                //Set fields to be accessible even when private
                field.setAccessible(true);

                final Class<?> fieldType = field.getType();

                if (fieldType.isEnum() && Enum.class.isAssignableFrom(fieldType)) {
                    //handle any enums here if you have any

                } else if (isMathNumberType(fieldType)) {
                    //System.out.println("*** Math number found, populating it: "+fieldType);                
                    field.set(target, getManufacturedPojo(fieldType));
                } //Check if the field is a collection
                else if (Collection.class.isAssignableFrom(fieldType)) {

                    //Get the generic type class of the collection
                    final Class<?> genericClass = getGenericClass(field);

                    //Check if the generic type of a list is abstract
                    if (Modifier.isAbstract(genericClass.getModifiers())) {

                        System.out.println("Abstract classes are not supported !!!");

                        // this stuff needs real class extending abstract one to work
                        //final List<Object> list = new ArrayList();
                        //list.add(populateAllIn(ClassExtendingAbstract.class));
                        //field.set(target, list);
                    } else {
                        final List<Object> list = new ArrayList();
                        list.add(populateAllFields(genericClass, exclusions));
                        field.set(target, list);
                    }

                } else if ((isSimpleType(fieldType) || isSimplePrimitiveWrapperType(fieldType))
                        && !fieldType.isEnum()) {
                    field.set(target, getManufacturedPojo(fieldType));
                } else if (!fieldType.isEnum()) {
                    field.set(target, populateAllFields(fieldType, exclusions));
                }
            } catch (IllegalAccessException | InstantiationException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }
    return target;
}

From source file:com.threewks.thundr.injection.InjectionContextImpl.java

@Override
public <T> InjectorBuilder<T> inject(Class<T> type) {

    if (!TypeIntrospector.isABasicType(type)
            && (type.isInterface() || Modifier.isAbstract(type.getModifiers()))) {
        throw new InjectionException(
                "Unable to inject the type '%s' - you cannot inject interfaces or abstract classes",
                type.getName());//from www  . ja  v  a 2 s  . co m
    }

    return new InjectorBuilder<T>(this, type);
}

From source file:org.apache.sling.scripting.sightly.render.AbstractRuntimeObjectModel.java

protected Method extractMethodInheritanceChain(Class type, Method m) {
    if (m == null || Modifier.isPublic(type.getModifiers())) {
        return m;
    }//from w w w  . ja va 2 s.co  m
    Class[] iFaces = type.getInterfaces();
    Method mp;
    for (Class<?> iFace : iFaces) {
        mp = getClassMethod(iFace, m);
        if (mp != null) {
            return mp;
        }
    }
    return getClassMethod(type.getSuperclass(), m);
}

From source file:org.grails.datastore.mapping.model.AbstractPersistentEntity.java

public void initialize() {
    initializeMappingProperties();// w w w  .jav a2 s .  c  o m
    owners = context.getMappingSyntaxStrategy().getOwningEntities(javaClass, context);
    persistentProperties = context.getMappingSyntaxStrategy().getPersistentProperties(this, context,
            getMapping());
    identity = resolveIdentifier();
    persistentPropertyNames = new ArrayList<String>();
    associations = new ArrayList();

    for (PersistentProperty persistentProperty : persistentProperties) {

        if (!(persistentProperty instanceof OneToMany)) {
            persistentPropertyNames.add(persistentProperty.getName());
        }

        if (persistentProperty instanceof Association) {
            associations.add((Association) persistentProperty);
        }

        propertiesByName.put(persistentProperty.getName(), persistentProperty);
    }

    Class superClass = javaClass.getSuperclass();
    if (superClass != null && !superClass.equals(Object.class)
            && !Modifier.isAbstract(superClass.getModifiers())) {
        parentEntity = context.addPersistentEntity(superClass);
    }

    getMapping().getMappedForm(); // initialize mapping

    if (mappingProperties.isVersioned()) {
        version = propertiesByName.get("version");
    }
    initialized = true;
}

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 ww  . ja  v  a  2 s . 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.apache.bval.cdi.BValExtension.java

public <A> void processAnnotatedType(final @Observes ProcessAnnotatedType<A> pat) {
    if (!isExecutableValidationEnabled) {
        return;/*from  ww w. j  a v  a  2 s  .c o m*/
    }

    final AnnotatedType<A> annotatedType = pat.getAnnotatedType();

    if (!annotatedTypeFilter.accept(annotatedType)) {
        return;
    }

    final Class<A> javaClass = annotatedType.getJavaClass();
    final int modifiers = javaClass.getModifiers();
    if (!javaClass.isInterface() && !Modifier.isFinal(modifiers) && !Modifier.isAbstract(modifiers)) {
        try {
            ensureFactoryValidator();
            try {
                final BeanDescriptor classConstraints = validator.getConstraintsForClass(javaClass);
                if (annotatedType.isAnnotationPresent(ValidateOnExecution.class)
                        || hasValidationAnnotation(annotatedType.getMethods())
                        || hasValidationAnnotation(annotatedType.getConstructors())
                        || classConstraints != null && (validBean && classConstraints.isBeanConstrained()
                                || validConstructors && !classConstraints.getConstrainedConstructors().isEmpty()
                                || validBusinessMethods && !classConstraints
                                        .getConstrainedMethods(MethodType.NON_GETTER).isEmpty()
                                || validGetterMethods && !classConstraints
                                        .getConstrainedMethods(MethodType.GETTER).isEmpty())) {
                    final BValAnnotatedType<A> bValAnnotatedType = new BValAnnotatedType<A>(annotatedType);
                    pat.setAnnotatedType(bValAnnotatedType);
                }
            } catch (final NoClassDefFoundError ncdfe) {
                // skip
            }
        } catch (final ValidationException ve) {
            LOGGER.log(Level.FINEST, ve.getMessage(), ve);
        } catch (final Exception e) { // just info
            LOGGER.log(Level.INFO, e.getMessage());
        }
    }
}

From source file:edu.cornell.med.icb.goby.modes.GenericToolsDriver.java

/**
 * Load the list of concrete modes./*  w w w.j  a  v  a  2s  .c  o m*/
 */
private void loadModeMap() {
    final Map<String, Class> modeMap = MODES_MAP;
    final Map<String, Class> shortModeMap = SHORT_MODES_MAP;
    final Map<Class, String> shortModeReverseMap = SHORT_MODES_REVERSE_MAP;
    final Set<String> allShortModes = new HashSet<String>();
    for (final String modeClassName : modesClassNamesList()) {
        try {
            LOG.debug("About to process modeClassName: " + modeClassName);
            final Class modeClass = Class.forName(modeClassName);
            if (Modifier.isAbstract(modeClass.getModifiers())) {
                // Ignore abstract classes
                continue;
            }
            // Since we're not abstract, we can make an instance
            final Object modeInstance = modeClass.newInstance();
            if (modeInstance instanceof AbstractCommandLineMode) {
                final String modeName = ((AbstractCommandLineMode) modeInstance).getModeName();
                final String shortModeName = ((AbstractCommandLineMode) modeInstance).getShortModeName();
                // Make sure the class has a static field "MODE_NAME"
                if (modeName != null) {
                    modeMap.put(modeName, modeClass);
                    if (shortModeName != null) {
                        if (!allShortModes.contains(shortModeName)) {
                            shortModeMap.put(shortModeName, modeClass);
                            shortModeReverseMap.put(modeClass, shortModeName);
                            allShortModes.add(shortModeName);
                        } else {
                            // Do not offer short versions for which there are duplicates. One needs
                            // to hand write versions of getShortModeName() for these classes.
                            shortModeReverseMap.remove(shortModeMap.get(shortModeName));
                            shortModeMap.remove(shortModeName);
                        }
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            System.err.println(
                    "Could find a class for " + modeClassName + " ClassNotFoundException: " + e.getMessage());
        } catch (IllegalAccessException e) {
            System.err.println("Could not find MODE_NAME for class " + modeClassName
                    + " IllegalAccessException: " + e.getMessage());
        } catch (InstantiationException e) {
            System.err.println("Could not find MODE_NAME for class " + modeClassName
                    + " InstantiationException: " + e.getMessage());
        }
    }
}

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  ww . j av  a2  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.batfish.common.plugin.PluginConsumer.java

private void loadPluginJar(Path path) {
    /*/*  ww w.j ava2s  .  c om*/
     * Adapted from
     * http://stackoverflow.com/questions/11016092/how-to-load-classes-at-
     * runtime-from-a-folder-or-jar Retrieved: 2016-08-31 Original Authors:
     * Kevin Crain http://stackoverflow.com/users/2688755/kevin-crain
     * Apfelsaft http://stackoverflow.com/users/1447641/apfelsaft License:
     * https://creativecommons.org/licenses/by-sa/3.0/
     */
    String pathString = path.toString();
    if (pathString.endsWith(".jar")) {
        try {
            URL[] urls = { new URL("jar:file:" + pathString + "!/") };
            URLClassLoader cl = URLClassLoader.newInstance(urls, _currentClassLoader);
            _currentClassLoader = cl;
            Thread.currentThread().setContextClassLoader(cl);
            JarFile jar = new JarFile(path.toFile());
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry element = entries.nextElement();
                String name = element.getName();
                if (element.isDirectory() || !name.endsWith(CLASS_EXTENSION)) {
                    continue;
                }
                String className = name.substring(0, name.length() - CLASS_EXTENSION.length()).replace("/",
                        ".");
                try {
                    cl.loadClass(className);
                    Class<?> pluginClass = Class.forName(className, true, cl);
                    if (!Plugin.class.isAssignableFrom(pluginClass)
                            || Modifier.isAbstract(pluginClass.getModifiers())) {
                        continue;
                    }
                    Constructor<?> pluginConstructor;
                    try {
                        pluginConstructor = pluginClass.getConstructor();
                    } catch (NoSuchMethodException | SecurityException e) {
                        throw new BatfishException(
                                "Could not find default constructor in plugin: '" + className + "'", e);
                    }
                    Object pluginObj;
                    try {
                        pluginObj = pluginConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        throw new BatfishException(
                                "Could not instantiate plugin '" + className + "' from constructor", e);
                    }
                    Plugin plugin = (Plugin) pluginObj;
                    plugin.initialize(this);

                } catch (ClassNotFoundException e) {
                    jar.close();
                    throw new BatfishException("Unexpected error loading classes from jar", e);
                }
            }
            jar.close();
        } catch (IOException e) {
            throw new BatfishException("Error loading plugin jar: '" + path.toString() + "'", e);
        }
    }
}

From source file:grails.core.ArtefactHandlerAdapter.java

/**
 * <p>Checks that class's name ends in the suffix specified for this handler.</p>
 * <p>Override for more complex criteria</p>
 * @param clazz The class to check/*w  w w .  j ava2s.c om*/
 * @return true if it is an artefact of this type
 */
public boolean isArtefactClass(@SuppressWarnings("rawtypes") Class clazz) {
    if (clazz == null)
        return false;

    boolean ok = clazz.getName().endsWith(artefactSuffix) && !Closure.class.isAssignableFrom(clazz);
    if (ok && !allowAbstract) {
        ok &= !Modifier.isAbstract(clazz.getModifiers());
    }
    return ok;
}