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:de.codesourcery.eve.skills.util.SpringBeanInjector.java

private void doInjectDependencies(Object obj)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    Class<?> currentClasz = obj.getClass();
    do {//from  w w  w  .ja  v a  2s .c om
        // inject fields
        for (Field f : currentClasz.getDeclaredFields()) {

            final int m = f.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isFinal(m)) {
                continue;
            }

            final Resource annot = f.getAnnotation(Resource.class);
            if (annot != null) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Setting field " + f.getName() + " with bean '"
                            + annot.name() + "'");
                }
                f.set(obj, getBean(annot.name()));
            }
        }

        // inject methods
        for (Method method : currentClasz.getDeclaredMethods()) {

            final int m = method.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isAbstract(m)) {
                continue;
            }

            if (method.getParameterTypes().length != 1) {
                continue;
            }

            if (!method.getName().startsWith("set")) {
                continue;
            }

            final Resource annot = method.getAnnotation(Resource.class);
            if (annot != null) {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Invoking setter method " + method.getName()
                            + " with bean '" + annot.name() + "'");
                }

                method.invoke(obj, getBean(annot.name()));
            }
        }

        currentClasz = currentClasz.getSuperclass();

    } while (currentClasz != null);
}

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param type the Class object, return false if null.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws IllegalArgumentException/*from  w w w  . j a  va 2  s .  c  o  m*/
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NegativeArraySizeException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(final Class<T> type) throws InstantiationException {
    if (type == null)
        return null;
    if (type.isArray())
        return (T) Array.newInstance(type.getComponentType(), 0);
    if (Void.class.equals(ClassUtils.primitiveToWrapper(type))) {
        try {
            Constructor<Void> c = Void.class.getDeclaredConstructor();
            c.setAccessible(true);

            return (T) c.newInstance();
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }

        return null;
    }

    if (type.isInterface()) {
        if (!Collection.class.isAssignableFrom(type))
            throw new InstantiationException(
                    "could not create instance, the type \"" + type.getName() + "\" is an interface.");
        if (List.class.isAssignableFrom(type))
            return (T) Lists.newArrayList();
        if (Map.class.isAssignableFrom(type))
            return (T) Maps.newHashMap();
        if (Set.class.isAssignableFrom(type))
            return (T) Sets.newHashSet();
    }

    if (type.isPrimitive()) {
        if (boolean.class.equals(type))
            return (T) Boolean.FALSE;
        if (char.class.equals(type))
            return (T) Character.valueOf(Character.MIN_VALUE);

        return (T) NumberUtils.valueOf("0", (Class<? extends Number>) type);
    }
    if (ClassUtils.isPrimitiveOrWrapper(type))
        return null;
    if (Modifier.isAbstract(type.getModifiers()))
        throw new InstantiationException(
                "could not create instance, the type \"" + type.getName() + "\" is an abstract class.");

    try {
        Constructor<?> c = type.getDeclaredConstructor();
        c.setAccessible(true);

        return (T) c.newInstance();
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }

    throw new InstantiationException("could not create instance, the default constructor of \"" + type.getName()
            + "()\" is not accessible ( or undefined ).");
}

From source file:com.adaptc.mws.plugins.testing.transformations.TestForTransformation.java

@Override
public void visit(ASTNode[] astNodes, SourceUnit source) {
    if (!(astNodes[0] instanceof AnnotationNode) || !(astNodes[1] instanceof AnnotatedNode)) {
        throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class");
    }/*from w ww.  j a  v  a2  s  .  com*/

    AnnotatedNode parent = (AnnotatedNode) astNodes[1];
    AnnotationNode node = (AnnotationNode) astNodes[0];
    if (!MY_TYPE.equals(node.getClassNode()) || !(parent instanceof ClassNode)) {
        return;
    }

    ClassNode classNode = (ClassNode) parent;
    if (classNode.isInterface() || Modifier.isAbstract(classNode.getModifiers())) {
        return;
    }

    boolean junit3Test = isJunit3Test(classNode);
    boolean spockTest = isSpockTest(classNode);
    boolean isJunit = classNode.getName().endsWith("Tests");

    if (!junit3Test && !spockTest && !isJunit)
        return;

    Expression value = node.getMember("value");
    ClassExpression ce;
    if (value instanceof ClassExpression) {
        ce = (ClassExpression) value;
        testFor(classNode, ce, true);
    } else {
        if (!junit3Test) {
            List<AnnotationNode> annotations = classNode.getAnnotations(MY_TYPE);
            if (annotations.size() > 0)
                return; // bail out, in this case it was already applied as a local transform
            // no explicit class specified try by convention
            String fileName = source.getName();
            String className = PluginsResourceUtils.getClassName(new FileSystemResource(fileName));
            if (className != null) {
                boolean isSpock = className.endsWith("Spec");
                String targetClassName = null;

                if (isJunit) {
                    targetClassName = className.substring(0, className.indexOf("Tests"));
                } else if (isSpock) {
                    targetClassName = className.substring(0, className.indexOf("Spec"));
                }

                if (targetClassName != null) {
                    Resource targetResource = findResourceForClassName(targetClassName);
                    if (targetResource != null) {
                        boolean isArtefact = false;
                        // Check for other artefact types
                        for (String artefactType : typeToTestMap.keySet()) {
                            if (targetClassName.endsWith(artefactType)) {
                                isArtefact = true;
                                testFor(classNode,
                                        new ClassExpression(
                                                new ClassNode(targetClassName, 0, ClassHelper.OBJECT_TYPE)),
                                        true);
                                break;
                            }
                        }
                        // Custom component?
                        if (!isArtefact)
                            testFor(classNode, new ClassExpression(
                                    new ClassNode(targetClassName, 0, ClassHelper.OBJECT_TYPE)), false);
                    }
                }
            }
        }
    }
}

From source file:br.ufpr.gres.core.classpath.ClassDetails.java

/**
 * Verify if a class is testable/*w  w w.j  a v a 2  s  .  c  o  m*/
 *
 * @return Return true if a class is testable; otherwise false
 * @throws java.lang.ClassNotFoundException
 * @throws java.io.IOException
 */
public boolean isTestable()
        throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException {
    Class c = getClassInstance();

    if (c.isInterface()) {
        logger.error("Can't apply mutation because " + className + " is 'interface'");
        return false;
    }

    if (Modifier.isAbstract(c.getModifiers())) {
        logger.error("Can't apply mutation because " + className + " is 'abstract' class");
        return false;
    }

    if (isGUI(c)) {
        logger.error("Can't apply mutation because " + className + " is 'GUI' class");
        return false;
    }
    if (isApplet(c)) {
        logger.error("Can't apply mutation because " + className + " is 'applet' class");
        return false;
    }

    return true;
}

From source file:grails.core.ArtefactHandlerAdapter.java

protected boolean isValidArtefactClassNode(ClassNode classNode, int modifiers) {
    return !classNode.isEnum() && !classNode.isInterface() && !Modifier.isAbstract(modifiers)
            && !(classNode instanceof InnerClassNode);
}

From source file:org.openmrs.module.openhmis.cashier.api.ReceiptNumberGeneratorFactory.java

/**
 * Locates and instantiates all classes that implement {@link IReceiptNumberGenerator} in the current classpath.
 * @return The instantiated receipt number generators.
 * @should Locate all classes that implement IReceiptNumberGenerator
 * @should Not throw an exception if the class instantiation fails
 * @should Use the existing instance for the currently defined generator
 *///from  w w w. jav a2  s  .  co m
public static IReceiptNumberGenerator[] locateGenerators() {
    // Search for any modules that define classes which implement the IReceiptNumberGenerator interface
    Reflections reflections = new Reflections("org.openmrs.module");
    List<Class<? extends IReceiptNumberGenerator>> classes = new ArrayList<Class<? extends IReceiptNumberGenerator>>();
    for (Class<? extends IReceiptNumberGenerator> cls : reflections
            .getSubTypesOf(IReceiptNumberGenerator.class)) {
        // We only care about public instantiable classes so ignore others
        if (!cls.isInterface() && !Modifier.isAbstract(cls.getModifiers())
                && Modifier.isPublic(cls.getModifiers())) {
            classes.add(cls);
        }
    }

    // Now attempt to instantiate each found class
    List<IReceiptNumberGenerator> instances = new ArrayList<IReceiptNumberGenerator>();
    for (Class<? extends IReceiptNumberGenerator> cls : classes) {
        if (generator != null && cls.equals(generator.getClass())) {
            instances.add(generator);
        } else {
            try {
                instances.add(cls.newInstance());
            } catch (Exception ex) {
                // We don't care about specific exceptions here.  Just log and ignore the class
                LOG.warn("Could not instantiate the '" + cls.getName() + "' class.  It will be ignored.");
            }
        }
    }

    // Finally, copy the instances to an array
    IReceiptNumberGenerator[] results = new IReceiptNumberGenerator[instances.size()];
    instances.toArray(results);

    return results;
}

From source file:ru.runa.af.web.system.TaskHandlerClassesInformation.java

private static void searchInJar(String jarName, JarInputStream jarInputStream) throws IOException {
    boolean matches = false;
    for (String patternFileName : BotStationResources.getTaskHandlerJarNames()) {
        if (FilenameUtils.wildcardMatch(jarName, patternFileName)) {
            matches = true;//from   ww  w .  j  a  v  a  2 s . com
            break;
        }
    }
    if (!matches) {
        log.debug("Ignored " + jarName);
        return;
    }
    log.info("Searching in " + jarName);
    ZipEntry entry;
    while ((entry = jarInputStream.getNextEntry()) != null) {
        if (entry.getName().endsWith(".class")) {
            try {
                String className = entry.getName();
                int lastIndexOfDotSymbol = className.lastIndexOf('.');
                className = className.substring(0, lastIndexOfDotSymbol).replace('/', '.');
                // If we can't load class - just move to next class.
                Class<?> someClass = ClassLoaderUtil.loadClass(className);
                if (TaskHandler.class.isAssignableFrom(someClass)
                        && !Modifier.isAbstract(someClass.getModifiers())) {
                    taskHandlerImplementationClasses.add(someClass.getCanonicalName());
                }
            } catch (Throwable e) {
                log.warn("Error on loading task handler for " + e.getMessage());
            }
        }
    }
}

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

public void initialize() {
    initializeMappingProperties();/*w w  w  . jav  a 2  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.apache.syncope.core.logic.init.ImplementationClassNamesLoader.java

@Override
public void load() {
    classNames = new EnumMap<>(Type.class);
    for (Type type : Type.values()) {
        classNames.put(type, new HashSet<String>());
    }//from  ww  w .  ja v  a2s . c om

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AssignableTypeFilter(Reportlet.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(TaskJob.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(SyncActions.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(PushActions.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(SyncCorrelationRule.class));
    // Remove once SYNCOPE-631 is done
    //scanner.addIncludeFilter(new AssignableTypeFilter(PushCorrelationRule.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(PropagationActions.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(Validator.class));

    for (BeanDefinition bd : scanner.findCandidateComponents(StringUtils.EMPTY)) {
        try {
            Class<?> clazz = ClassUtils.resolveClassName(bd.getBeanClassName(),
                    ClassUtils.getDefaultClassLoader());
            boolean isAbsractClazz = Modifier.isAbstract(clazz.getModifiers());

            if (Reportlet.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.REPORTLET).add(clazz.getName());
            }

            if (TaskJob.class.isAssignableFrom(clazz) && !isAbsractClazz
                    && !SyncJob.class.isAssignableFrom(clazz) && !PushJob.class.isAssignableFrom(clazz)) {

                classNames.get(Type.TASKJOB).add(bd.getBeanClassName());
            }

            if (SyncActions.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.SYNC_ACTIONS).add(bd.getBeanClassName());
            }

            if (PushActions.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.PUSH_ACTIONS).add(bd.getBeanClassName());
            }

            if (SyncCorrelationRule.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.SYNC_CORRELATION_RULE).add(bd.getBeanClassName());
            }

            // Uncomment when SYNCOPE-631 is done
            /* if (PushCorrelationRule.class.isAssignableFrom(clazz) && !isAbsractClazz) {
             * classNames.get(Type.PUSH_CORRELATION_RULES).add(metadata.getClassName());
             * } */
            if (PropagationActions.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.PROPAGATION_ACTIONS).add(bd.getBeanClassName());
            }

            if (Validator.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.VALIDATOR).add(bd.getBeanClassName());
            }
        } catch (Throwable t) {
            LOG.warn("Could not inspect class {}", bd.getBeanClassName(), t);
        }
    }
    classNames = Collections.unmodifiableMap(classNames);

    LOG.debug("Implementation classes found: {}", classNames);
}

From source file:com.retroduction.carma.resolvers.util.TestCaseInstantiationVerifier.java

public HashSet<String> determineUnloadableTestClassNames(Set<String> fqTestClassNames) {

    HashSet<String> unloadableClasses = new HashSet<String>();

    for (String testClassName : fqTestClassNames) {

        try {//from  w  w w .j a  v a2 s. c  o  m

            Class<?> testClass = this.getLoader().loadClass(testClassName);

            if (Modifier.isAbstract(testClass.getModifiers())
                    || Modifier.isInterface(testClass.getModifiers())) {
                this.log.info("Skipping abstract class or interface in test set:" + testClassName);
                unloadableClasses.add(testClassName);
                continue;
            }

        } catch (Exception e) {
            this.log.warn("Skipping class in test set due to class loading problem:" + testClassName);
            this.log.debug(e);
            unloadableClasses.add(testClassName);
            continue;
        } catch (NoClassDefFoundError e) {
            this.log.warn("Skipping class in test set due to class loading problem:" + testClassName);
            this.log.debug(e);
            unloadableClasses.add(testClassName);
            continue;
        }

    }

    return unloadableClasses;
}