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.norconex.commons.lang.ClassFinder.java

private static String resolveName(ClassLoader loader, String rawName, Class<?> superClass) {
    String className = rawName;// w  w w.ja v  a  2  s  . c o m
    if (!rawName.endsWith(".class") || className.contains("$")) {
        return null;
    }
    className = className.replaceAll("[\\\\/]", ".");
    className = StringUtils.removeStart(className, ".");
    className = StringUtils.removeEnd(className, ".class");

    try {
        Class<?> clazz = loader.loadClass(className);
        // load only concrete implementations
        if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers())
                && superClass.isAssignableFrom(clazz)) {
            return clazz.getName();
        }
    } catch (ClassNotFoundException e) {
        LOG.error("Invalid class: " + className, e);
    } catch (NoClassDefFoundError e) {
        LOG.debug("Invalid class: " + className, e);
    }
    return null;
}

From source file:org.apache.tajo.engine.function.FunctionLoader.java

/**
 * This method finds and build FunctionDesc for the legacy function and UD(A)F system.
 *
 * @return A list of FunctionDescs/*from w w  w .j  a  v  a 2  s .  c  o  m*/
 */
public static List<FunctionDesc> findLegacyFunctions() {
    List<FunctionDesc> sqlFuncs = new ArrayList<>();

    Set<Class> functionClasses = ClassUtil.findClasses(Function.class, "org.apache.tajo.engine.function");

    for (Class eachClass : functionClasses) {
        if (eachClass.isInterface() || Modifier.isAbstract(eachClass.getModifiers())) {
            continue;
        }
        Function function = null;
        try {
            function = (Function) eachClass.newInstance();
        } catch (Exception e) {
            LOG.warn(eachClass + " cannot instantiate Function class because of " + e.getMessage(), e);
            continue;
        }
        String functionName = function.getClass().getAnnotation(Description.class).functionName();
        String[] synonyms = function.getClass().getAnnotation(Description.class).synonyms();
        String description = function.getClass().getAnnotation(Description.class).description();
        String detail = function.getClass().getAnnotation(Description.class).detail();
        String example = function.getClass().getAnnotation(Description.class).example();
        TajoDataTypes.Type returnType = function.getClass().getAnnotation(Description.class).returnType();
        ParamTypes[] paramArray = function.getClass().getAnnotation(Description.class).paramTypes();

        String[] allFunctionNames = null;
        if (synonyms != null && synonyms.length > 0) {
            allFunctionNames = new String[1 + synonyms.length];
            allFunctionNames[0] = functionName;
            System.arraycopy(synonyms, 0, allFunctionNames, 1, synonyms.length);
        } else {
            allFunctionNames = new String[] { functionName };
        }

        for (String eachFunctionName : allFunctionNames) {
            for (ParamTypes params : paramArray) {
                ParamOptionTypes[] paramOptionArray;
                if (params.paramOptionTypes() == null
                        || params.paramOptionTypes().getClass().getAnnotation(ParamTypes.class) == null) {
                    paramOptionArray = new ParamOptionTypes[0];
                } else {
                    paramOptionArray = params.paramOptionTypes().getClass().getAnnotation(ParamTypes.class)
                            .paramOptionTypes();
                }

                TajoDataTypes.Type[] paramTypes = params.paramTypes();
                if (paramOptionArray.length > 0)
                    paramTypes = params.paramTypes().clone();

                for (int i = 0; i < paramOptionArray.length + 1; i++) {
                    FunctionDesc functionDesc = new FunctionDesc(eachFunctionName, function.getClass(),
                            function.getFunctionType(), CatalogUtil.newSimpleDataType(returnType),
                            paramTypes.length == 0 ? CatalogUtil.newSimpleDataTypeArray()
                                    : CatalogUtil.newSimpleDataTypeArray(paramTypes));

                    functionDesc.setDescription(description);
                    functionDesc.setExample(example);
                    functionDesc.setDetail(detail);
                    sqlFuncs.add(functionDesc);

                    if (i != paramOptionArray.length) {
                        paramTypes = new TajoDataTypes.Type[paramTypes.length
                                + paramOptionArray[i].paramOptionTypes().length];
                        System.arraycopy(params.paramTypes(), 0, paramTypes, 0, paramTypes.length);
                        System.arraycopy(paramOptionArray[i].paramOptionTypes(), 0, paramTypes,
                                paramTypes.length, paramOptionArray[i].paramOptionTypes().length);
                    }
                }
            }
        }
    }

    return sqlFuncs;
}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

public static boolean isTypeInstatiable(Class<?> type) {
    int modifiers = type.getModifiers();
    if (!(Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers))) {
        try {/*from w  ww .  ja v a  2  s . c o  m*/
            Constructor<?> noArgConstructor = type.getConstructor();
            return Modifier.isPublic(noArgConstructor.getModifiers());
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        }
    }
    return false;
}

From source file:org.apache.tapestry.enhance.DefaultComponentClassEnhancer.java

/**
 *  Searches the class for abstract methods, returning the first found.
 *  Records non-abstract methods in the implementedMethods set.
 * /*from  ww w.  j  a v a2 s . c om*/
 **/

private Method checkForAbstractMethods(Class current, Set implementedMethods) {
    boolean debug = LOG.isDebugEnabled();

    if (debug)
        LOG.debug("Searching for abstract methods in " + current);

    Method[] methods = current.getDeclaredMethods();

    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];

        if (debug)
            LOG.debug("Checking " + m);

        boolean isAbstract = Modifier.isAbstract(m.getModifiers());

        MethodSignature s = new MethodSignature(m);

        if (isAbstract) {
            if (implementedMethods.contains(s))
                continue;

            return m;
        }

        implementedMethods.add(s);
    }

    return null;
}

From source file:org.eclipse.wb.internal.core.databinding.ui.editor.contentproviders.ChooseClassUiContentProvider.java

/**
 * This method calculate state and sets or clear error message. Subclasses maybe override this
 * method for observe special states./*  w w  w  . ja  v a2  s  .c o  m*/
 */
protected void calculateFinish() {
    String className = getClassName();
    // route events
    if (m_router != null) {
        m_router.handle();
    }
    // check state
    if (className.length() == 0) {
        // empty class
        setErrorMessage(m_configuration.getEmptyClassErrorMessage());
    } else {
        // check clear of default value (maybe not class)
        if (m_configuration.isDefaultString(className) || className.equals(m_configuration.getClearValue())
                || ArrayUtils.indexOf(m_configuration.getDefaultValues(), className) != -1) {
            setErrorMessage(null);
            return;
        }
        // check load class
        Class<?>[][] constructorsParameters = m_configuration.getConstructorsParameters();
        String errorMessagePrefix = m_configuration.getErrorMessagePrefix();
        //
        boolean noConstructor = false;
        try {
            Class<?> testClass = loadClass(className);
            // check permissions
            int modifiers = testClass.getModifiers();
            if (!Modifier.isPublic(modifiers)) {
                setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateNotPublic);
                return;
            }
            if (!m_configuration.isChooseInterfaces() && Modifier.isAbstract(modifiers)) {
                setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateAbstract);
                return;
            }
            // check constructor
            if (m_checkClasses) {
                m_checkClasses = false;
                if (constructorsParameters != null) {
                    for (int i = 0; i < constructorsParameters.length; i++) {
                        Class<?>[] constructorParameters = constructorsParameters[i];
                        for (int j = 0; j < constructorParameters.length; j++) {
                            Class<?> constructorParameterClass = constructorParameters[j];
                            if (constructorParameterClass.isArray()) {
                                String parameterClassName = constructorParameterClass.getComponentType()
                                        .getName();
                                if (parameterClassName.startsWith("org.eclipse")) {
                                    constructorParameters[j] = Array
                                            .newInstance(loadClass(parameterClassName), new int[1]).getClass();
                                }
                            } else {
                                String parameterClassName = constructorParameterClass.getName();
                                if (parameterClassName.startsWith("org.eclipse")) {
                                    constructorParameters[j] = loadClass(parameterClassName);
                                }
                            }
                        }
                    }
                }
            }
            if (constructorsParameters != null) {
                noConstructor = true;
                for (int i = 0; i < constructorsParameters.length; i++) {
                    try {
                        testClass.getConstructor(constructorsParameters[i]);
                        noConstructor = false;
                        break;
                    } catch (SecurityException e) {
                    } catch (NoSuchMethodException e) {
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateNotExist);
            return;
        }
        // prepare error message for constructor
        if (noConstructor) {
            StringBuffer parameters = new StringBuffer(errorMessagePrefix);
            parameters.append(Messages.ChooseClassUiContentProvider_validatePublicConstructor);
            for (int i = 0; i < constructorsParameters.length; i++) {
                Class<?>[] constructorParameters = constructorsParameters[i];
                if (i > 0) {
                    parameters.append(" ");
                }
                parameters.append(ClassUtils.getShortClassName(className));
                parameters.append("(");
                for (int j = 0; j < constructorParameters.length; j++) {
                    if (j > 0) {
                        parameters.append(", ");
                    }
                    parameters.append(ClassUtils.getShortClassName(constructorParameters[j]));
                }
                parameters.append(")");
            }
            parameters.append(".");
            setErrorMessage(parameters.toString());
        } else {
            setErrorMessage(null);
        }
    }
}

From source file:com.github.geequery.codegen.ast.JavaMethod.java

public String toCode(JavaUnit main) {
    // if (code != null)
    // return code;
    StringBuilder sb = new StringBuilder();
    // ?/* w  w w  .  ja v  a2s .c  om*/
    sb.append(super.generateComments());
    // ?Annotation
    for (String s : annotations) {
        sb.append(s);
        sb.append("\r\n\t");
        // line++;
    }
    JavaUnit.appendModifier(sb, this.modifier, main.isInterface());
    if (typeParameters != null && typeParameters.length > 0) {
        sb.append("<");
        for (int n = 0; n < typeParameters.length; n++) {
            if (n > 0)
                sb.append(',');
            sb.append(typeParameters[n]);
        }
        sb.append(">");
    }
    if (returnType == null) {
        sb.append("void ");
    } else {
        sb.append(main.getJavaClassName(returnType)).append(" ");
    }
    sb.append(name);
    sb.append("(");
    if (!inputArgs.isEmpty()) {
        Iterator<String> iter = inputArgs.keySet().iterator();
        String key = iter.next(); // key???
        JavaParameter param = inputArgs.get(key);
        param.genetateCode(this, main, sb, varArg && !iter.hasNext());
        for (; iter.hasNext();) {
            key = iter.next();
            sb.append(",");
            param = inputArgs.get(key);
            if (param == null)
                continue;
            param.genetateCode(this, main, sb, varArg && !iter.hasNext());
        }
    }
    sb.append(")");
    // 
    if (this.throws_ != null && throws_.size() > 0) {
        sb.append("throws ");
        for (int i = 0; i < throws_.size(); i++) {
            if (i > 0)
                sb.append(',');
            IClass t = throws_.get(i);
            sb.append(main.getJavaClassName(t));
        }
    }
    if (Modifier.isAbstract(this.modifier) || main.isInterface()) {
        sb.append(";");
        return sb.toString();
    }
    sb.append("{\r\n");
    boolean hasReturn = false;
    for (String str : super.getContent()) {
        sb.append("\t\t");
        sb.append(str).append("\r\n");
        if (checkReturn && str.startsWith("return ")) {
            hasReturn = true;
        }
    }
    if (checkReturn && returnType != null && !hasReturn) {
        sb.append("\t\treturn " + IClassUtil.defaultValue(returnType) + ";\n");
    }
    sb.append("\t}\r\n");
    return sb.toString();
}

From source file:org.lmn.fc.common.utilities.pending.Utilities.java

/***********************************************************************************************
 * Show the Member Modifiers.//  w w  w  .  j  a v a2s .  c o  m
 *
 * @param member
 *
 * @return String
 */

public static String showModifiers(final Member member) {
    final int modifiers;
    final StringBuffer buffer;

    buffer = new StringBuffer();

    if (member != null) {
        modifiers = member.getModifiers();

        if (Modifier.isAbstract(modifiers)) {
            buffer.append("Abstract ");
        }

        if (Modifier.isFinal(modifiers)) {
            buffer.append("Final ");
        }

        if (Modifier.isInterface(modifiers)) {
            buffer.append("Interface ");
        }

        if (Modifier.isNative(modifiers)) {
            buffer.append("Native ");
        }

        if (Modifier.isPrivate(modifiers)) {
            buffer.append("Private ");
        }

        if (Modifier.isProtected(modifiers)) {
            buffer.append("Protected ");
        }

        if (Modifier.isPublic(modifiers)) {
            buffer.append("Public ");
        }

        if (Modifier.isStatic(modifiers)) {
            buffer.append("Static ");
        }

        if (Modifier.isStrict(modifiers)) {
            buffer.append("Strict ");
        }

        if (Modifier.isSynchronized(modifiers)) {
            buffer.append("Synchronized ");
        }

        if (Modifier.isTransient(modifiers)) {
            buffer.append("Transient ");
        }

        if (Modifier.isVolatile(modifiers)) {
            buffer.append("Volatile ");
        }
    }

    return (buffer.toString().trim());
}

From source file:org.dllearner.core.AnnComponentManager.java

private AnnComponentManager() {
    if (componentClassNames == null) {
        componentClassNames = new ArrayList<>();
        if (reflectionScanner == null) {
            org.apache.log4j.Logger.getLogger(Reflections.class).setLevel(Level.OFF);
            reflectionScanner = new Reflections("org.dllearner");
        }//from w  w w.  j av a  2 s  . c  o m
        Set<Class<? extends Component>> componentClasses = reflectionScanner.getSubTypesOf(Component.class);
        Set<Class<?>> componentAnnClasses = reflectionScanner.getTypesAnnotatedWith(ComponentAnn.class, true);
        for (Class<?> clazz : Sets.intersection(componentClasses, componentAnnClasses)) {
            if (!Modifier.isAbstract(clazz.getModifiers()))
                componentClassNames.add(clazz.getCanonicalName());
        }
        for (Class<?> clazz : Sets.difference(componentClasses, componentAnnClasses)) {
            if (!Modifier.isAbstract(clazz.getModifiers()))
                logger.debug("Warning: " + clazz.getCanonicalName()
                        + " implements Component but is not annotated, ignored");
        }
    }
    // conversion of class strings to objects
    components = new TreeSet<>((Comparator<Class<? extends Component>>) (o1, o2) -> {
        return o1.getName().compareTo(o2.getName());
    });
    componentNames = new DualHashBidiMap<>();
    componentNamesShort = new DualHashBidiMap<>();
    for (String componentClassName : componentClassNames) {
        try {
            Class<? extends Component> component = Class.forName(componentClassName)
                    .asSubclass(Component.class);
            components.add(component);
            componentNames.put(component, getName(component));
            componentNamesShort.put(component, getShortName(component));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

From source file:ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition.java

@SuppressWarnings("unchecked")
void populateScanAlso(Set<Class<? extends IBase>> theScanAlso) {
    for (ScannedField next : myScannedFields) {
        if (IBase.class.isAssignableFrom(next.getElementType())) {
            if (next.getElementType().isInterface() == false
                    && Modifier.isAbstract(next.getElementType().getModifiers()) == false) {
                theScanAlso.add((Class<? extends IBase>) next.getElementType());
            }// w w  w.  j  av  a  2s .co m
        }
        for (Class<? extends IBase> nextChildType : next.getChoiceTypes()) {
            if (nextChildType.isInterface() == false
                    && Modifier.isAbstract(nextChildType.getModifiers()) == false) {
                theScanAlso.add(nextChildType);
            }
        }
    }
}

From source file:org.eclipse.winery.repository.export.ZipExporter.java

/**
 * Writes a complete CSAR containing all necessary things reachable from the given service
 * template/*  w  w w.  jav  a  2  s .c  o m*/
 * 
 * @param id the id of the service template to export
 * @param out the outputstream to write to
 * @throws JAXBException
 */
public void writeZip(TOSCAComponentId entryId, OutputStream out)
        throws ArchiveException, IOException, XMLStreamException, JAXBException {
    ZipExporter.logger.trace("Starting CSAR export with {}", entryId.toString());

    Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>();
    Collection<String> definitionNames = new ArrayList<>();

    final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

    TOSCAExportUtil exporter = new TOSCAExportUtil();
    Map<String, Object> conf = new HashMap<>();

    ExportedState exportedState = new ExportedState();

    TOSCAComponentId currentId = entryId;
    do {
        logger.info("begin to scan class:" + System.currentTimeMillis());
        Reflections reflections = new Reflections("org.eclipse.winery.repository.ext");
        Set<Class<? extends ExportFileGenerator>> implenmetions = reflections
                .getSubTypesOf(org.eclipse.winery.repository.ext.export.custom.ExportFileGenerator.class);
        logger.info("end to scan class:" + System.currentTimeMillis());
        Iterator<Class<? extends ExportFileGenerator>> it = implenmetions.iterator();
        Collection<TOSCAComponentId> referencedIds = null;

        String defName = ZipExporter.getDefinitionsPathInsideCSAR(currentId);
        definitionNames.add(defName);

        zos.putArchiveEntry(new ZipArchiveEntry(defName));

        try {
            referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null);
        } catch (IllegalStateException e) {
            // thrown if something went wrong inside the repo
            out.close();
            // we just rethrow as there currently is no error stream.
            throw e;
        }
        zos.closeArchiveEntry();

        while (it.hasNext()) {
            Class<? extends ExportFileGenerator> exportClass = it.next();
            logger.trace("the " + exportClass.toString() + "begin to write file");
            try {
                if (!Modifier.isAbstract(exportClass.getModifiers())) {
                    ExportFileGenerator fileGenerator = exportClass.newInstance();
                    referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, fileGenerator);
                }
            } catch (InstantiationException e) {
                logger.error("export error occur while instancing " + exportClass.toString(), e);
                out.close();
            } catch (IllegalAccessException e) {
                logger.error("export error occur", e);
                out.close();
            }
        }

        exportedState.flagAsExported(currentId);
        exportedState.flagAsExportRequired(referencedIds);

        currentId = exportedState.pop();
    } while (currentId != null);

    // if we export a ServiceTemplate, data for the self-service portal might exist
    if (entryId instanceof ServiceTemplateId) {
        this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap);
        addCsarMeta((ServiceTemplateId) entryId, zos);
    }

    // write custom file
    CustomizedFileInfos customizedResult = null;
    if (entryId instanceof ServiceTemplateId) {
        customizedResult = this.exportCustomFiles((ServiceTemplateId) entryId, zos);
    }

    // write manifest directly after the definitions to have it more at the beginning of the ZIP
    // rather than having it at the very end
    this.addManifest(entryId, definitionNames, refMap, zos);
    this.addManiYamlfest(entryId, exporter.getYamlExportDefResultList(), refMap, zos, exporter);
    this.addCheckSumFest(
            getCheckSums(exporter.getYamlExportDefResultList(), customizedResult.getCustomizedFileResults()),
            zos);
    // used for generated XSD schemas
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tFactory.newTransformer();
    } catch (TransformerConfigurationException e1) {
        ZipExporter.logger.debug(e1.getMessage(), e1);
        throw new IllegalStateException("Could not instantiate transformer", e1);
    }

    // write all referenced files
    for (RepositoryFileReference ref : refMap.keySet()) {
        String archivePath = refMap.get(ref);
        ZipExporter.logger.trace("Creating {}", archivePath);
        ArchiveEntry archiveEntry = new ZipArchiveEntry("xml/" + archivePath);
        zos.putArchiveEntry(archiveEntry);
        if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) {
            ZipExporter.logger.trace("Special treatment for generated XSDs");
            Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument();
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(zos);
            try {
                transformer.transform(source, result);
            } catch (TransformerException e) {
                ZipExporter.logger.debug("Could not serialize generated xsd", e);
            }
        } else {
            try (InputStream is = Repository.INSTANCE.newInputStream(ref)) {
                IOUtils.copy(is, zos);
            } catch (Exception e) {
                ZipExporter.logger.error("Could not copy file content to ZIP outputstream", e);
            }
        }

        // add plan files/artifact templantes to yaml folder
        updatePlanDef(archivePath, ref, zos, customizedResult.getPlanInfos());

        zos.closeArchiveEntry();
    }

    addPlan2Zip(customizedResult.getPlanInfos(), zos);
    this.addNamespacePrefixes(zos);

    zos.finish();
    zos.close();
}