Example usage for java.lang Class getModifiers

List of usage examples for java.lang Class getModifiers

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native int getModifiers();

Source Link

Document

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

Usage

From source file:org.integratedmodelling.thinklab.plugin.ThinklabPlugin.java

protected void loadInstanceImplementationConstructors() throws ThinklabPluginException {

    String ipack = this.getClass().getPackage().getName() + ".implementations";

    for (Class<?> cls : MiscUtilities.findSubclasses(IInstanceImplementation.class, ipack, getClassLoader())) {

        String concept = null;/*from  w  ww .  j a  v a  2s . co  m*/

        /*
         * lookup annotation, ensure we can use the class
         */
        if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()))
            continue;

        /*
         * lookup implemented concept
         */
        for (Annotation annotation : cls.getAnnotations()) {
            if (annotation instanceof InstanceImplementation) {
                concept = ((InstanceImplementation) annotation).concept();
            }
        }

        if (concept != null) {

            String[] cc = concept.split(",");

            for (String ccc : cc) {
                logger().info("registering class " + cls + " as implementation for instances of type " + ccc);
                KnowledgeManager.get().registerInstanceImplementationClass(ccc, cls);
            }
        }
    }
}

From source file:org.broadinstitute.gatk.queue.extensions.gatk.GATKExtensionsGenerator.java

/**
 * Writes the dependents to a scala wrapper that will compile and get picked up by BCEL.
 * BCEL was missing some classes, such as Enums, when they were defined in the other generated classes.
 * This generated wrapper makes sure they are explicitly seen by BCEL.
 * @param dependents Explicit dependencies that need to be packaged.
 * @throws IOException If the file cannot be written.
 *///from   ww  w .ja v  a 2 s . c om
private void writeDependencies(SortedSet<Class<?>> dependents) throws IOException {
    // Include the enclosing classes too.  Scala will be looking for them.
    SortedSet<Class<?>> enclosings = new TreeSet<Class<?>>(classComparator);
    for (Class<?> dependent : dependents)
        for (Class<?> enclosing = dependent; enclosing != null; enclosing = enclosing.getEnclosingClass())
            enclosings.add(enclosing);
    dependents = enclosings;

    // Oh, and include the classes defined on methods too!
    enclosings = new TreeSet<Class<?>>(classComparator);
    for (Class<?> dependent : dependents) {
        for (Method method : dependent.getDeclaredMethods()) {
            JVMUtils.addGenericTypes(enclosings, method.getGenericReturnType());
            for (Type parameterType : method.getGenericParameterTypes())
                JVMUtils.addGenericTypes(enclosings, parameterType);
            for (Type exceptionType : method.getGenericExceptionTypes())
                JVMUtils.addGenericTypes(enclosings, exceptionType);
        }
    }
    dependents = enclosings;

    // Generate the dependents.
    String className = "GATKClassDependencies";
    StringBuilder classes = new StringBuilder();

    for (Class<?> dependent : dependents) {
        if (dependent.isArray())
            continue;
        if (ArgumentField.isBuiltIn(dependent))
            continue;
        if (!Modifier.isPublic(dependent.getModifiers()))
            continue;
        if (classes.length() > 0)
            classes.append(",").append(NEWLINE);
        String typeParams = getScalaTypeParams(dependent);
        classes.append("classOf[").append(dependent.getName().replace("$", ".")).append(typeParams).append("]");
    }
    String content = String.format(GATK_DEPENDENCIES_TEMPLATE, GATK_EXTENSIONS_PACKAGE_NAME, className,
            classes);
    writeFile(GATK_EXTENSIONS_PACKAGE_NAME + "." + className, content);
}

From source file:org.obsidian.test.TestAbstract.java

public <T> void appendEqualityMethodTypes(Class<T> type) {
    Boolean ignore = false;// ww w  .  j a  va 2s  .  c o m

    //Make sure: not already in Equality Method Types
    for (Class c : getEqualityMethodTypes()) {
        if (type.toString().compareToIgnoreCase(c.toString()) == 0) {
            ignore = true;
        }
    }

    //Make sure: not a Throwable
    Class superClass = type.getSuperclass();//first check immediate super

    if (superClass != null) {
        while (!superClass.equals(Object.class)) {//while still has superclasses

            //#### Patch Submitted by Joanna Illing (illing.joanna@gmail.com) 2/13/13
            if (superClass.equals(Throwable.class)) {
                ignore = true;//if Throwable: ignore
            }
            superClass = superClass.getSuperclass();
        }

    }

    if (type.getSimpleName().compareToIgnoreCase("string") == 0) {
        ignore = true;
    }

    if (type.getSimpleName().compareToIgnoreCase("Exception") == 0) {
        ignore = true;
    }

    if (type.getSimpleName().compareToIgnoreCase("Throwable") == 0) {
        ignore = true;
    }

    if (Modifier.isStatic(type.getModifiers()) && type.getSuperclass() != null) {
        appendDynamicImports(type.getSuperclass());
    }

    if (!ignore) {
        getEqualityMethodTypes().add(type);
    }

}

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

/**
 * Generate the bytecode for a bean proxy for the given type.
 *///from  w  w w .j a v  a2 s.c  o  m
protected BCClass generateProxyBeanBytecode(Class type, boolean runtime) {
    if (Modifier.isFinal(type.getModifiers()))
        return null;
    if (ImplHelper.isManagedType(null, type))
        return null;

    // we can only generate a valid proxy if there is a copy constructor
    // or a default constructor
    Constructor cons = findCopyConstructor(type);
    if (cons == null) {
        Constructor[] cs = type.getConstructors();
        for (int i = 0; cons == null && i < cs.length; i++)
            if (cs[i].getParameterTypes().length == 0)
                cons = cs[i];
        if (cons == null)
            return null;
    }

    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyBean.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, true);
    addProxyBeanMethods(bc, type, cons);
    if (!proxySetters(bc, type))
        return null;
    addWriteReplaceMethod(bc, runtime);
    return bc;
}

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

/**
 * Create an instance of the specified class and instantiate it's data from the given data source using the RDF
 * instance specified by the given URI//from w w w. j a va 2  s.  c  om
 * @param theClass the class to create
 * @param theId the id of the RDF individual containing the data for the new instance
 * @param theSource the KB to get the RDF data from
 * @param <T> the type of the instance to create
 * @return a new instance
 * @throws InvalidRdfException thrown if the class does not support RDF JPA operations, or does not provide sufficient access to its fields/data.
 * @throws DataSourceException thrown if there is an error while retrieving data from the graph
 */
public static <T> T fromRdf(Class<T> theClass, SupportsRdfId.RdfKey theId, DataSource theSource)
        throws InvalidRdfException, DataSourceException {
    T aObj;
    long start = System.currentTimeMillis(), start1 = System.currentTimeMillis();
    try {
        aObj = Empire.get().instance(theClass);
    } catch (ConfigurationException ex) {
        aObj = null;
    } catch (ProvisionException ex) {
        aObj = null;
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Tried to get instance of class in {} ms ", (System.currentTimeMillis() - start));
    }
    start = System.currentTimeMillis();

    if (aObj == null) {
        // this means Guice construction failed, which is not surprising since that's not going to be the default.
        // so we'll try our own reflect based creation or create bytecode for an interface.

        try {
            long istart = System.currentTimeMillis();
            if (theClass.isInterface() || Modifier.isAbstract(theClass.getModifiers())) {
                aObj = com.clarkparsia.empire.codegen.InstanceGenerator.generateInstanceClass(theClass)
                        .newInstance();

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("CodeGenerated instance in {} ms. ", (System.currentTimeMillis() - istart));
                }
            } else {
                aObj = theClass.newInstance();

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("CodeGenerated instance in {} ms. ", (System.currentTimeMillis() - istart));
                }
            }
        } catch (InstantiationException e) {
            throw new InvalidRdfException("Cannot create instance of bean, should have a default constructor.",
                    e);
        } catch (IllegalAccessException e) {
            throw new InvalidRdfException("Could not access default constructor for class: " + theClass, e);
        } catch (Exception e) {
            throw new InvalidRdfException("Cannot create an instance of bean", e);
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Got reflect instance of class {} ms ", (System.currentTimeMillis() - start1));
        }

        start = System.currentTimeMillis();
    }

    asSupportsRdfId(aObj).setRdfId(theId);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Has rdfId {} ms", (System.currentTimeMillis() - start1));
    }

    start = System.currentTimeMillis();

    Class<T> aNewClass = determineClass(theClass, aObj, theSource);

    if (!aNewClass.equals(aObj.getClass())) {
        try {
            aObj = aNewClass.newInstance();
        } catch (InstantiationException e) {
            throw new InvalidRdfException("Cannot create instance of bean, should have a default constructor.",
                    e);
        } catch (IllegalAccessException e) {
            throw new InvalidRdfException("Could not access default constructor for class: " + theClass, e);
        } catch (Exception e) {
            throw new InvalidRdfException("Cannot create an instance of bean", e);
        }
        asSupportsRdfId(aObj).setRdfId(theId);
    }

    T fromRdf = fromRdf(aObj, theSource);
    return fromRdf;
}

From source file:org.obsidian.test.TestAbstract.java

public <T> void appendDynamicImports(Class<T> classToImport) {
    boolean shouldBeIgnored = false;

    //Make sure: not already in dynamic imports
    for (String s : getDynamicImports()) {
        if (s.compareToIgnoreCase(classToImport.getName().replaceAll("\\$", ".")) == 0) {
            shouldBeIgnored = true;/*ww w  .j  ava2 s  .c o m*/
        }
    }

    if (!classToImport.isPrimitive() && !classToImport.isArray()) {
        //make sure: not in imports from constants
        for (String s : Content.IMPORTS) {
            if (s.compareToIgnoreCase(classToImport.getName()) == 0) {
                shouldBeIgnored = true;
            }

        }

        //make sure: not in same package
        if (classToImport.getPackage().toString()
                .compareToIgnoreCase(classTested.getPackage().toString()) == 0) {

            //#### Patch Submitted by Michael Cole (micole.3@gmail.com) 2/13/13
            if (!(classToImport.isMemberClass() || classToImport.isEnum() || classToImport.isLocalClass())) {
                shouldBeIgnored = true;
            }

        }

        //make sure not private
        if (Modifier.isPrivate(classToImport.getModifiers())) {
            shouldBeIgnored = true;
        }

        //make sure: not importing from java.lang unless at least 3 deep 
        //ex)java.lang.reflect
        String[] packageStructure = classToImport.getPackage().getName().split("\\.");
        int packageDepth = packageStructure.length;

        //if dataInputStream java.lang
        if (packageStructure[0].compareToIgnoreCase("java") == 0
                && packageStructure[1].compareToIgnoreCase("lang") == 0) {

            //and less than three deep
            if (packageDepth < 3) {
                shouldBeIgnored = true;
                classToImport.getName();
            }
        }
    } else {
        shouldBeIgnored = true;
        if (classToImport.isArray() && !classToImport.getComponentType().isPrimitive()) {
            appendDynamicImports(classToImport.getComponentType());
        }
    }

    //if: not already in imports and not in same package
    if (!shouldBeIgnored) {
        //add to dynamic imports
        String importName = classToImport.getName();
        importName = importName.replaceAll("\\$", ".");
        getDynamicImports().add(importName);
    }
}

From source file:org.integratedmodelling.thinklab.plugin.ThinklabPlugin.java

protected void loadLiteralValidators() throws ThinklabException {

    String ipack = this.getClass().getPackage().getName() + ".literals";

    for (Class<?> cls : MiscUtilities.findSubclasses(ParsedLiteralValue.class, ipack, getClassLoader())) {

        String concept = null;//from   www . j a  v  a2 s . com
        String xsd = null;

        /*
         * lookup annotation, ensure we can use the class
         */
        if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()))
            continue;

        /*
         * lookup implemented concept
         */
        for (Annotation annotation : cls.getAnnotations()) {
            if (annotation instanceof LiteralImplementation) {
                concept = ((LiteralImplementation) annotation).concept();
                xsd = ((LiteralImplementation) annotation).xsd();
            }
        }

        if (concept != null) {

            logger().info("registering class " + cls + " as implementation for literals of type " + concept);

            KnowledgeManager.get().registerLiteralImplementationClass(concept, cls);
            if (!xsd.equals(""))

                logger().info("registering XSD type mapping: " + xsd + " -> " + concept);
            KnowledgeManager.get().registerXSDTypeMapping(xsd, concept);
        }

    }

}

From source file:org.zaproxy.zap.control.AddOnLoader.java

public <T> List<T> getImplementors(AddOn ao, String packageName, Class<T> classType) {
    Class<?> cls = null;
    List<T> listClass = new ArrayList<>();

    List<ClassNameWrapper> classNames;
    if (ao != null) {
        classNames = this.getJarClassNames(ao, packageName);
    } else {/*from   w  w  w.ja va 2  s.co m*/
        classNames = this.getClassNames(packageName, classType);
    }
    for (ClassNameWrapper classWrapper : classNames) {
        try {
            cls = classWrapper.getCl().loadClass(classWrapper.getClassName());
            // abstract class or interface cannot be constructed.
            if (Modifier.isAbstract(cls.getModifiers()) || Modifier.isInterface(cls.getModifiers())) {
                continue;
            }
            if (classType.isAssignableFrom(cls)) {
                @SuppressWarnings("unchecked")
                Constructor<T> c = (Constructor<T>) cls.getConstructor();
                listClass.add(c.newInstance());

            }
        } catch (Throwable e) {
            // Often not an error
            logger.debug(e.getMessage());
        }
    }
    return listClass;
}

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

private Class<?> getExceptionClassToUse(Throwable exception) {
    /*//from  w  ww .j  av  a  2  s .  c  om
    we can only catch a public class.
    for "readability" of tests, it shouldn't be a mock one either
      */
    Class<?> ex = exception.getClass();
    while (!Modifier.isPublic(ex.getModifiers()) || EvoSuiteMock.class.isAssignableFrom(ex)
            || ex.getCanonicalName().startsWith("com.sun.")) {
        ex = ex.getSuperclass();
    }
    return ex;
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getObject(Class claz, List<Type> heirarchies) throws Exception {

    if (claz.isEnum())
        return claz.getEnumConstants()[0];

    if (isMap(claz)) {
        return getMapValue(claz, claz.getTypeParameters(), heirarchies);
    } else if (isCollection(claz)) {
        return getListSetValue(claz, claz.getTypeParameters(), heirarchies);
    } else if (claz.isInterface() || Modifier.isAbstract(claz.getModifiers())) {
        return null;
    }//from w  w  w .  j a  v  a 2 s  . c  o m

    if (heirarchies.contains(claz) || heirarchies.size() >= 2)
        return null;
    heirarchies.add(claz);

    Constructor cons = null;
    try {
        cons = claz.getConstructor(new Class[] {});
    } catch (Exception e) {
        getLog().error("No public no-args constructor found for class " + claz.getName());
        return null;
    }

    Object object = cons.newInstance(new Object[] {});
    List<Field> allFields = getAllFields(claz);

    for (Field field : allFields) {

        if (Modifier.isStatic(field.getModifiers()))
            continue;

        if (!field.isAccessible()) {
            field.setAccessible(true);
        }

        List<Type> fheirlst = new ArrayList<Type>(heirarchies);

        if (isDebugEnabled())
            getLog().info("Parsing Class " + getHeirarchyStr(fheirlst) + " field " + field.getName() + " type "
                    + field.getType().equals(boolean.class));

        if (isPrimitive(field.getType())) {
            field.set(object, getPrimitiveValue(field.getType()));
        } else if (isMap(field.getType())) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            field.set(object, getMapValue(field.getType(), type.getActualTypeArguments(), fheirlst));
        } else if (isCollection(field.getType())) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            field.set(object, getListSetValue(field.getType(), type.getActualTypeArguments(), fheirlst));
        } else if (!claz.equals(field.getType())) {
            Object fieldval = getObject(field.getType(), fheirlst);
            field.set(object, fieldval);
        } else if (claz.equals(field.getType())) {
            if (isDebugEnabled())
                getLog().info("Ignoring recursive fields...");
        }
    }
    return object;
}