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:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

/**
 * Between two getter methods defined for a given property, both declared in the same class, picks one
 *
 * @param first  the first getter/*from   ww  w . j  a  va  2 s .c  o  m*/
 * @param second the second getter
 * @return the winning getter
 */
private static Method pickGetter(Method first, Method second) {
    //if one is an interface, and one is not, the concrete implementation wins
    if (Modifier.isInterface(first.getModifiers()) && !Modifier.isInterface(second.getModifiers())) {
        return second;
    }
    if (!Modifier.isInterface(first.getModifiers()) && Modifier.isInterface(second.getModifiers())) {
        return first;
    }
    //if one is abstract and the other is not, the non-abstract one wins
    if (Modifier.isAbstract(first.getModifiers()) && !Modifier.isAbstract(second.getModifiers())) {
        return second;
    }
    if (!Modifier.isAbstract(first.getModifiers()) && Modifier.isAbstract(second.getModifiers())) {
        return first;
    }
    //given a hierarchy, the child wins
    if (first.getReturnType().isAssignableFrom(second.getReturnType())) {
        return second;
    }
    if (second.getReturnType().isAssignableFrom(first.getReturnType())) {
        return first;
    }
    if (!hasAnnotations(first) && hasAnnotations(second)) {
        return second;
    }
    if (hasAnnotations(first) && !hasAnnotations(second)) {
        return first;
    }
    return first;
}

From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java

/**
 * Construct a class//  ww w. j av  a2s  .c  om
 * @param <T> template type
 * @param theClass
 * @param allowPrivateConstructor true if should allow private constructors
 * @return the instance
 */
public static <T> T newInstance(Class<T> theClass, boolean allowPrivateConstructor) {
    if (!allowPrivateConstructor) {
        return newInstance(theClass);
    }
    try {
        Constructor<?>[] constructorArray = theClass.getDeclaredConstructors();
        for (Constructor<?> constructor : constructorArray) {
            if (constructor.getGenericParameterTypes().length == 0) {
                if (allowPrivateConstructor) {
                    constructor.setAccessible(true);
                }
                return (T) constructor.newInstance();
            }
        }
        //why cant we find a constructor???
        throw new RuntimeException("Why cant we find a constructor for class: " + theClass);
    } catch (Throwable e) {
        if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) {
            throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!",
                    e);
        }
        throw new RuntimeException("Problem with class: " + theClass, e);
    }
}

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

/**
 * @return a reference to the public static serializableInstance() method of
 * clazz, if there is one; otherwise, returns null.
 *//*from w  w  w . j av  a2 s  .com*/
private Method serializableInstanceMethod(Class clazz) {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
        if ("serializableInstance".equals(method.getName())) {
            Class[] parameterTypes = method.getParameterTypes();

            if (!(parameterTypes.length == 0)) {
                continue;
            }

            if (!(Modifier.isStatic(method.getModifiers()))) {
                continue;
            }

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

            return method;
        }
    }

    return null;
}

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

/**
 * Returns a reference to the public static serializableInstance() method of
 * clazz, if there is one; otherwise, returns null.
 *//*from   w  w w.j a va2  s  . co m*/
public Method serializableInstanceMethod(Class clazz) {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
        if ("serializableInstance".equals(method.getName())) {
            Class[] parameterTypes = method.getParameterTypes();

            if (!(parameterTypes.length == 0)) {
                continue;
            }

            if (!(Modifier.isStatic(method.getModifiers()))) {
                continue;
            }

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

            return method;
        }
    }

    return null;
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

private TDefinitions createDefinitionsByThirdparty(final List<String> errors, Path defsPath) {
    TDefinitions defs = null;//from   w w w  .  j  a va2  s.c om
    try {
        Reflections reflections = new Reflections("org.eclipse.winery.repository.ext");
        Set<Class<? extends DefinitionGenerator>> implenmetions = reflections
                .getSubTypesOf(org.eclipse.winery.repository.ext.imports.custom.DefinitionGenerator.class);
        Iterator<Class<? extends DefinitionGenerator>> it = implenmetions.iterator();
        while (it.hasNext()) {
            Class<? extends DefinitionGenerator> impl = it.next();
            if (!Modifier.isAbstract(impl.getModifiers())) {
                DefinitionGenerator generator = impl.newInstance();
                if (generator.accept(defsPath)) {
                    try {
                        defs = generator.makeDefinitions(defsPath);
                    } catch (Exception e) {
                        CSARImporter.logger.error("error occurs while make defintions by: " + impl.toString());
                        continue;
                    }
                } else
                    CSARImporter.logger
                            .info(impl.toString() + " refuse to deal with file: " + defsPath.getFileName());
            }
        }

    } catch (Exception e) {
        errors.add("Could not parse definitions " + defsPath.getFileName() + " ");
        CSARImporter.logger.debug("parse error", e);
    }
    return defs;
}

From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java

/**
 * Generates and returns source code for importing packages that are
 * required by the persister helper this class is generating.
 * //from w w  w . ja  v a 2  s .c  o  m
 * @param visitedClass
 *            The {@link SPObject} class that is being visited by the
 *            annotation processor.
 * @param constructorImports
 *            The {@link Set} of packages that visitedClass uses in its
 *            {@link Constructor} annotated constructor and need to be
 *            imported.
 * @param mutatorImports
 *            The {@link Multimap} of setter methods to packages that
 *            visitedClass uses in its {@link Mutator} annotated methods and
 *            needs to be imported.
 * @return The source code for the generated imports.
 */
private String generateImports(Class<? extends SPObject> visitedClass, Set<String> constructorImports,
        Multimap<String, String> mutatorImports) {
    final String helperPackage = visitedClass.getPackage().getName() + "."
            + PersisterHelperFinder.GENERATED_PACKAGE_NAME;

    // Using a TreeSet here to sort imports alphabetically.
    Set<String> allImports = new TreeSet<String>();
    if (!Modifier.isAbstract(visitedClass.getModifiers())) {
        allImports.addAll(constructorImports);
    }
    allImports.addAll(mutatorImports.values());

    StringBuilder sb = new StringBuilder();

    // XXX Need to import any additional classes this generated persister helper
    // class requires, aside from those needed in visitedClass.
    allImports.add(List.class.getName());
    allImports.add(visitedClass.getName());
    allImports.add(SPPersistenceException.class.getName());
    allImports.add(SPPersister.class.getName());
    allImports.add(SessionPersisterSuperConverter.class.getName());
    allImports.add(SPObject.class.getName());
    allImports.add(DataType.class.getName());
    allImports.addAll(importedClassNames);

    for (String pkg : allImports) {
        // No need to import java.lang as it is automatically imported.
        // No need to import package if the persister helper is already
        // in the package.
        // Also want to keep array classes out
        if (!pkg.startsWith("java.lang") && !pkg.startsWith("[L")) {
            // Nested classes, enums, etc. will be separated by the "$"
            // character but we need to change them to "." so it can be
            // imported correctly.
            String pkgName = pkg.replaceAll("\\$", ".");

            // Only import the package if it is not the same one
            // that the persister helper exists in.
            int index = pkgName.lastIndexOf(".");
            if (index == -1) {
                index = pkgName.length();
            }
            if (!pkgName.substring(0, index).equals(helperPackage)) {
                niprintln(sb, "import " + pkgName + ";");
            }
        }
    }

    return sb.toString();
}

From source file:eu.stratosphere.api.java.typeutils.TypeExtractor.java

@SuppressWarnings("unchecked")
public static <X> TypeInformation<X> getForClass(Class<X> clazz) {
    Validate.notNull(clazz);//from ww  w  . j a va2  s  . c o  m

    // check for abstract classes or interfaces
    if (Modifier.isInterface(clazz.getModifiers())
            || (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray())) {
        throw new InvalidTypesException("Interfaces and abstract classes are not valid types.");
    }

    // check for arrays
    if (clazz.isArray()) {

        // primitive arrays: int[], byte[], ...
        PrimitiveArrayTypeInfo<X> primitiveArrayInfo = PrimitiveArrayTypeInfo.getInfoFor(clazz);
        if (primitiveArrayInfo != null) {
            return primitiveArrayInfo;
        }

        // basic type arrays: String[], Integer[], Double[]
        BasicArrayTypeInfo<X, ?> basicArrayInfo = BasicArrayTypeInfo.getInfoFor(clazz);
        if (basicArrayInfo != null) {
            return basicArrayInfo;
        }

        // object arrays
        else {
            return ObjectArrayTypeInfo.getInfoFor(clazz);
        }
    }

    // check for writable types
    if (Writable.class.isAssignableFrom(clazz)) {
        return (TypeInformation<X>) WritableTypeInfo.getWritableTypeInfo((Class<? extends Writable>) clazz);
    }

    // check for basic types
    TypeInformation<X> basicTypeInfo = BasicTypeInfo.getInfoFor(clazz);
    if (basicTypeInfo != null) {
        return basicTypeInfo;
    }

    // check for subclasses of Value
    if (Value.class.isAssignableFrom(clazz)) {
        Class<? extends Value> valueClass = clazz.asSubclass(Value.class);
        return (TypeInformation<X>) ValueTypeInfo.getValueTypeInfo(valueClass);
    }

    // check for subclasses of Tuple
    if (Tuple.class.isAssignableFrom(clazz)) {
        throw new InvalidTypesException(
                "Type information extraction for tuples cannot be done based on the class.");
    }

    // return a generic type
    return new GenericTypeInfo<X>(clazz);
}

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;//  w ww .j a  va2s. c om
        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.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * Auto-detect the class names of the implementation of <code>com.sun.tools.doclets.Taglet</code> class from a
 * given jar file.//w ww .j a  v  a 2s.c  o  m
 * <br/>
 * <b>Note</b>: <code>JAVA_HOME/lib/tools.jar</code> is a requirement to find
 * <code>com.sun.tools.doclets.Taglet</code> class.
 *
 * @param jarFile not null
 * @return the list of <code>com.sun.tools.doclets.Taglet</code> class names from a given jarFile.
 * @throws IOException if jarFile is invalid or not found, or if the <code>JAVA_HOME/lib/tools.jar</code>
 * is not found.
 * @throws ClassNotFoundException if any
 * @throws NoClassDefFoundError if any
 */
protected static List<String> getTagletClassNames(File jarFile)
        throws IOException, ClassNotFoundException, NoClassDefFoundError {
    List<String> classes = getClassNamesFromJar(jarFile);
    ClassLoader cl;

    // Needed to find com.sun.tools.doclets.Taglet class
    File tools = new File(System.getProperty("java.home"), "../lib/tools.jar");
    if (tools.exists() && tools.isFile()) {
        cl = new URLClassLoader(new URL[] { jarFile.toURI().toURL(), tools.toURI().toURL() }, null);
    } else {
        cl = new URLClassLoader(new URL[] { jarFile.toURI().toURL() }, null);
    }

    List<String> tagletClasses = new ArrayList<String>();

    Class<?> tagletClass = cl.loadClass("com.sun.tools.doclets.Taglet");
    for (String s : classes) {
        Class<?> c = cl.loadClass(s);

        if (tagletClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) {
            tagletClasses.add(c.getName());
        }
    }

    return tagletClasses;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Find get methods with no params. All getters that aren't Native, Static,
 * Abstract, Synthetic, or Bridge are returned.
 * //from w w  w  .ja v  a  2s .c o m
 * @param clazz
 *          the clazz
 * @return the list
 */
public synchronized static List<Method> findGetMethodsWithNoParams(Class<?> clazz) {

    /* if a cache already exists simply return it */
    List<Method> returnMethods = cachedMethods.get(clazz);

    if (returnMethods == null) {
        /* create a new cache and return it */
        returnMethods = new ArrayList<Method>();

        for (Method method : findAllMethods(clazz)) {

            // check for compiler introduced methods, as well as native methods.
            // simply ignore these methods, as they are probably not what we are
            // looking for.

            int modifiers = method.getModifiers();

            if (Modifier.isNative(modifiers) //
                    || Modifier.isStatic(modifiers) //
                    || Modifier.isAbstract(modifiers) //
                    || method.isSynthetic() //
                    || method.isBridge()) {
                continue;
            }

            // if its a getter then add it to the list
            if (isIs(method) || isGetter(method)) {
                if (!doesMethodHaveParams(method)) {
                    returnMethods.add(method);
                }
            }
        }

        cachedMethods.put(clazz, returnMethods);
    }

    return returnMethods;
}