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:fr.exanpe.tapestry.tldgen.taglib.builder.StructureBuilder.java

/**
 * Builds the output taglib structure/*w  ww .  ja  v a  2 s  .  c o m*/
 * 
 * @param rootPackage the root package to look the components for
 * @param supportedPackages all sub packages to scan
 * @param urls the urls used to scan the packages
 * @return the structure containing the information on the taglib to generate
 * @throws MojoExecutionException if any unexpected error occurs
 */
public Taglib build(String rootPackage, String[] supportedPackages, URL[] urls) throws MojoExecutionException {
    Taglib taglib = new Taglib();

    log.debug("Creating taglib object model...");

    for (String subPackage : supportedPackages) {
        String pkgname = rootPackage + "." + subPackage;

        log.debug("Processing taglib for full package named : " + pkgname);

        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(pkgname))).setUrls(urls)
                .setScanners(new TypesScanner()));

        Store store = reflections.getStore();

        // Return classes anaylised by TypeScanner
        Multimap<String, String> classes = store.getStoreMap().values().iterator().next();

        log.debug(String.format("%s classes to analyse for %s package...", classes.keySet().size(), pkgname));

        // Loop on found classes
        for (final String s : classes.keySet()) {
            Class<?> c;
            try {
                log.debug(String.format("Load class %s into classloader", s));
                c = Thread.currentThread().getContextClassLoader().loadClass(s);
            } catch (ClassNotFoundException e) {
                // should not happen as it has just been parsed by Reflection...
                log.error(e);
                throw new MojoExecutionException("Class loader internal error for class :" + s, e);
            }

            if (!c.isAnnotation() && !c.isAnonymousClass() && !c.isEnum() && !c.isInterface()
                    && !c.isLocalClass() && !c.isMemberClass() && !c.isSynthetic()
                    && !Modifier.isAbstract(c.getModifiers())) {
                log.debug("Processing Tag : " + c.getName());

                Tag tag = buildTagFromClass(rootPackage, c);
                taglib.getTags().add(tag);
            }
        }
    }

    log.debug("Taglib object model completed");
    return taglib;
}

From source file:org.apache.cactus.integration.maven.CactusScanner.java

/**
 * @param theClassName the fully qualified name of the class to check
 * @param theClasspath the classpaths needed to load the test classes
 * @return true if the class is a JUnit test case
 *///from  w w w.  j a v a 2s .  co  m
private boolean isJUnitTestCase(String theClassName, Path theClasspath) {
    Class clazz = loadClass(theClassName, theClasspath);
    if (clazz == null) {
        return false;
    }

    Class testCaseClass = null;
    try {
        testCaseClass = clazz.getClassLoader().loadClass(TestCase.class.getName());
    } catch (ClassNotFoundException e) {
        log.debug("Cannot load class", e);
        return false;
    }

    if (!testCaseClass.isAssignableFrom(clazz)) {
        log.debug("Not a JUnit test as class [" + theClassName + "] does " + "not inherit from ["
                + TestCase.class.getName() + "]");
        return false;
    }

    // the class must not be abstract
    if (Modifier.isAbstract(clazz.getModifiers())) {
        log.debug("Not a JUnit test as class [" + theClassName + "] is " + "abstract");
        return false;
    }

    // the class must have at least one test, i.e. a public method
    // starting with "test" and that takes no parameters
    boolean hasTestMethod = false;
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().startsWith("test") && (methods[i].getReturnType() == Void.TYPE)
                && (methods[i].getParameterTypes().length == 0)) {
            hasTestMethod = true;
            break;
        }
    }

    if (!hasTestMethod) {
        log.debug("Not a JUnit test as class [" + theClassName + "] has "
                + "no method that start with \"test\", returns void and has " + "no parameters");
        return false;
    }

    return true;
}

From source file:org.apache.syncope.core.provisioning.java.data.ImplementationDataBinderImpl.java

@Override
public void update(final Implementation implementation, final ImplementationTO implementationTO) {
    SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidImplementation);

    if (implementation.getType() != null && implementation.getType() != implementationTO.getType()) {
        sce.getElements().add("ImplementationType cannot be changed");
        throw sce;
    }//from ww  w .j a v a  2 s  . co  m

    if (StringUtils.isBlank(implementationTO.getBody())) {
        sce.getElements().add("No actual implementation provided");
        throw sce;
    }

    BeanUtils.copyProperties(implementationTO, implementation);

    if (implementation.getEngine() == ImplementationEngine.JAVA) {
        Class<?> base = null;
        switch (implementation.getType()) {
        case REPORTLET:
            base = Reportlet.class;
            break;

        case ACCOUNT_RULE:
            base = AccountRule.class;
            break;

        case PASSWORD_RULE:
            base = PasswordRule.class;
            break;

        case ITEM_TRANSFORMER:
            base = ItemTransformer.class;
            break;

        case TASKJOB_DELEGATE:
            base = SchedTaskJobDelegate.class;
            break;

        case RECON_FILTER_BUILDER:
            base = ReconFilterBuilder.class;
            break;

        case LOGIC_ACTIONS:
            base = LogicActions.class;
            break;

        case PROPAGATION_ACTIONS:
            base = PropagationActions.class;
            break;

        case PULL_ACTIONS:
            base = PullActions.class;
            break;

        case PUSH_ACTIONS:
            base = PushActions.class;
            break;

        case PULL_CORRELATION_RULE:
            base = PullCorrelationRule.class;
            break;

        case VALIDATOR:
            base = Validator.class;
            break;

        case RECIPIENTS_PROVIDER:
            base = RecipientsProvider.class;
            break;

        default:
        }

        if (base == null) {
            sce.getElements().add("No Java interface found for " + implementation.getType());
            throw sce;
        }

        if (implementation.getType() == ImplementationType.REPORTLET) {
            ReportletConf reportlet = POJOHelper.deserialize(implementation.getBody(), ReportletConf.class);
            if (reportlet == null) {
                sce.getElements().add("Could not deserialize as ReportletConf");
                throw sce;
            }
        } else if (implementation.getType() == ImplementationType.ACCOUNT_RULE
                || implementation.getType() == ImplementationType.PASSWORD_RULE
                || implementation.getType() == ImplementationType.PULL_CORRELATION_RULE) {

            RuleConf rule = POJOHelper.deserialize(implementation.getBody(), RuleConf.class);
            if (rule == null) {
                sce.getElements()
                        .add("Could not deserialize as neither Account, Password nor PullCorrelation RuleConf");
                throw sce;
            }
        } else {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(implementation.getBody());
            } catch (Exception e) {
                LOG.error("Class '{}' not found", implementation.getBody(), e);
                sce.getElements().add("No Java class found: " + implementation.getBody());
                throw sce;
            }
            if (!base.isAssignableFrom(clazz)) {
                sce.getElements()
                        .add("Java class " + implementation.getBody() + " must comply with " + base.getName());
                throw sce;
            }
            if (Modifier.isAbstract(clazz.getModifiers())) {
                sce.getElements().add("Java class " + implementation.getBody() + " is abstract");
                throw sce;
            }
        }
    }
}

From source file:org.hisp.dhis.webwork.configuration.UrlXmlConfigurationProvider.java

protected boolean verifyAction(String className, String name, Location loc) {
    try {/*from ww  w.jav a  2  s.  c om*/
        Class clazz = ObjectFactory.getObjectFactory().getClassInstance(className);
        if (ObjectFactory.getObjectFactory().isNoArgConstructorRequired()) {
            if (!Modifier.isPublic(clazz.getModifiers())) {
                LOG.error("Action class [" + className + "] is not public, skipping action [" + name + "]");
                return false;
            }
            clazz.getConstructor(new Class[] {});
        }
        return true;
    } catch (ClassNotFoundException e) {
        LOG.error("Action class [" + className + "] not found, skipping action [" + name + "] at " + loc, e);
        return false;
    } catch (NoSuchMethodException e) {
        LOG.error("Action class [" + className + "] does not have a public no-arg constructor,"
                + " skipping action [" + name + "] at " + loc, e);
        return false;
    } catch (Exception ex) {
        throw new ConfigurationException(ex, loc);
    }
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Finds all classes inside the stated scope that implement
 * TetradSerializable and serializes them out to the getCurrentDirectory()
 * directory. Abstract methods and interfaces are skipped over. For all
 * other classes C, it is assumed that C has a static constructor of the
 * following form://from  w w  w  .  j  a  va2  s. c  om
 * <pre>
 *     public static C serializableInstance() {
 *         // Returns an instance of C. May be a mind-numbingly simple
 *         // instance, no need to get fancy.
 *     }
 * </pre>
 * The instance returned may be mind-numbingly simple; there is no need to
 * get fancy. It may change over time. The point is to make sure that
 * instances serialized out with earlier versions load with the
 * currentDirectory version.
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 */
public void serializeCurrentDirectory() throws RuntimeException {
    clearCurrentDirectory();
    @SuppressWarnings("Convert2Diamond")
    Map<String, List<String>> classFields = new TreeMap<>();

    // Get the classes that implement SerializationCanonicalizer.
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    System.out.println(
            "Serializing exemplars of instantiable TetradSerializable " + "in " + getSerializableScope() + ".");
    System.out.println("Writing serialized examplars to " + getCurrentDirectory());

    int index = -1;

    for (Object aClass : classes) {
        Class clazz = (Class) aClass;

        if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
            continue;
        }

        if (Modifier.isAbstract(clazz.getModifiers())) {
            continue;
        }

        if (Modifier.isInterface(clazz.getModifiers())) {
            continue;
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0 && serializableInstanceMethod(clazz) == null) {
            throw new RuntimeException("Class " + clazz + " does not "
                    + "\nhave a public static serializableInstance constructor.");
        }

        if (++index % 50 == 0) {
            System.out.println(index);
        }

        System.out.print(".");

        serializeClass(clazz, classFields);
    }

    try {
        File file = new File(getCurrentDirectory(), "class_fields.ser");
        FileOutputStream out = new FileOutputStream(file);
        ObjectOutputStream objOut = new ObjectOutputStream(out);
        objOut.writeObject(classFields);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("\nFinished serializing exemplars.");
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Finds all classes inside the stated scope that implement
 * TetradSerializable and serializes them out to the getCurrentDirectory()
 * directory. Abstract methods and interfaces are skipped over. For all
 * other classes C, it is assumed that C has a static constructor of the
 * following form:/*from   w w w .  ja va 2s  . c  o m*/
 * <pre>
 *     public static C serializableInstance() {
 *         // Returns an instance of C. May be a mind-numbingly simple
 *         // instance, no need to get fancy.
 *     }
 * </pre>
 * The instance returned may be mind-numbingly simple; there is no need to
 * get fancy. It may change over time. The point is to make sure that
 * instances serialized out with earlier versions load with the
 * currentDirectory version.
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 */
public void serializeCurrentDirectory() throws RuntimeException {
    clearCurrentDirectory();
    Map<String, List<String>> classFields = new TreeMap<String, List<String>>();

    // Get the classes that implement SerializationCanonicalizer.
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    System.out.println(
            "Serializing exemplars of instantiable TetradSerializable " + "in " + getSerializableScope() + ".");
    System.out.println("Writing serialized examplars to " + getCurrentDirectory());

    int index = -1;

    for (Object aClass : classes) {
        Class clazz = (Class) aClass;

        if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
            continue;
        }

        if (Modifier.isAbstract(clazz.getModifiers())) {
            continue;
        }

        if (Modifier.isInterface(clazz.getModifiers())) {
            continue;
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0 && serializableInstanceMethod(clazz) == null) {
            throw new RuntimeException("Class " + clazz + " does not "
                    + "\nhave a public static serializableInstance constructor.");
        }

        if (++index % 50 == 0) {
            System.out.println(index);
        }

        System.out.print(".");

        serializeClass(clazz, classFields);
    }

    try {
        File file = new File(getCurrentDirectory(), "class_fields.ser");
        FileOutputStream out = new FileOutputStream(file);
        ObjectOutputStream objOut = new ObjectOutputStream(out);
        objOut.writeObject(classFields);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("\nFinished serializing exemplars.");
}

From source file:ome.services.graphs.AnnotationGraphSpec.java

/**
 * Performs sanity checks on the annotation entries found in {@link ExtendedMetadata}.
 * Primarily, this prevents new annotation types from not being properly specified
 * in spec.xml./*from   w  ww. j a  va2 s  .c  o  m*/
 */
@Override
public void setExtendedMetadata(ExtendedMetadata em) {
    super.setExtendedMetadata(em);

    // First calculate the number of unique top-level paths
    List<String> uniquePaths = new ArrayList<String>();
    for (GraphEntry entry : entries) {
        String topLevel = entry.path("")[0];
        if (!uniquePaths.contains(topLevel)) {
            uniquePaths.add(topLevel);
        }
    }

    // Now we check if this represents all the annotation types
    // in the system.
    Set<Class<Annotation>> types = em.getAnnotationTypes();
    if (types.size() != uniquePaths.size()) {
        throw new FatalBeanException("Mismatch between anntotations defined and those found: " + entries + "<> "
                + em.getAnnotationTypes());
    }

    TYPE: for (Class<Annotation> type : types) {
        String simpleName = type.getSimpleName();
        for (int i = 0; i < entries.size(); i++) {
            GraphEntry entry = entries.get(i);
            if (entry.path("").length > 1) {
                // This not an annotation, but some subpath
                // ignore it.
                continue;
            }
            if (simpleName.equals(entry.getName().substring(1))) {
                this.types[i] = type;
                if (Modifier.isAbstract(type.getModifiers())) {
                    this.isAbstract[i] = true;
                }
                continue TYPE;
            }
        }
        throw new FatalBeanException("Could not find entry: " + simpleName);
    }
}

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

/**
 * Return an object of the specified type to allow access to the
 * provider-specific API. If the Bean Validation provider implementation
 * does not support the specified class, the ValidationException is thrown.
 *
 * @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.
 *//*  w  ww. j av a  2s . co  m*/
public <T> T unwrap(final Class<T> type) {
    if (type.isInstance(this)) {
        @SuppressWarnings("unchecked")
        final T result = (T) this;
        return result;
    }

    // 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.isInterface() || Modifier.isAbstract(type.getModifiers()))) {
        return newInstance(type);
    }
    try {
        final Class<?> cls = ClassUtils.getClass(type.getName() + "Impl");
        if (type.isAssignableFrom(cls)) {
            @SuppressWarnings("unchecked")
            T result = (T) newInstance(cls);
            return result;
        }
    } catch (ClassNotFoundException e) {
        // do nothing
    }
    throw new ValidationException("Type " + type + " not supported");
}

From source file:com.bstek.dorado.config.xml.XmlParserHelper.java

private void collectConcereteXmlParsersByClassName(Context context, Class<?> targetType, Class<?> implType,
        List<XmlParserInfo> xmlParserInfos, boolean checkType) throws Exception {
    if (Modifier.isAbstract(implType.getModifiers()) || !targetType.isAssignableFrom(implType)) {
        if (checkType) {
            throw new IllegalArgumentException(
                    implType.getName() + " is not a sub type of " + targetType.getName() + ".");
        }// www  .  j  a  v  a  2 s  . c  om
        return;
    }

    XmlNodeInfo concereteXmlNodeInfo = getXmlNodeInfo(implType);
    if (concereteXmlNodeInfo != null) {
        for (XmlParserInfo xmlParserInfo : doGetXmlParserInfosByBeanType(context, implType,
                concereteXmlNodeInfo)) {
            xmlParserInfos.add(xmlParserInfo);
        }
    }
}

From source file:lineage2.gameserver.scripts.Scripts.java

/**
 * Method load.//from   w w  w .ja  va2 s.  c om
 * @param classes List<Class<?>>
 * @param target String
 * @return boolean
 */
private boolean load(List<Class<?>> classes, String target) {
    Collection<File> scriptFiles = Collections.emptyList();

    File file = new File(Config.DATAPACK_ROOT, "data/scripts/" + target.replace(".", "/") + ".java");
    if (file.isFile()) {
        scriptFiles = new ArrayList<>(1);
        scriptFiles.add(file);
    } else {
        file = new File(Config.DATAPACK_ROOT, "data/scripts/" + target);
        if (file.isDirectory()) {
            scriptFiles = FileUtils.listFiles(file, FileFilterUtils.suffixFileFilter(".java"),
                    FileFilterUtils.directoryFileFilter());
        }
    }

    if (scriptFiles.isEmpty()) {
        return false;
    }

    Class<?> clazz;
    boolean success = compiler.compile(scriptFiles);
    if (success) {
        MemoryClassLoader classLoader = compiler.getClassLoader();
        for (String name : classLoader.getLoadedClasses()) {
            if (name.contains(ClassUtils.INNER_CLASS_SEPARATOR)) {
                continue;
            }

            try {
                clazz = classLoader.loadClass(name);
                if (Modifier.isAbstract(clazz.getModifiers())) {
                    continue;
                }
                classes.add(clazz);
            } catch (ClassNotFoundException e) {
                success = false;
                _log.error("Scripts: Can't load script class: " + name, e);
            }
        }
        classLoader.clear();
    }

    return success;
}