Example usage for java.lang.reflect Modifier isPublic

List of usage examples for java.lang.reflect Modifier isPublic

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isPublic.

Prototype

public static boolean isPublic(int mod) 

Source Link

Document

Return true if the integer argument includes the public modifier, false otherwise.

Usage

From source file:org.apache.nifi.processors.kafka.pubsub.KafkaProcessorUtils.java

private static Set<String> getPublicStaticStringFieldValues(final Class<?>... classes) {
    final Set<String> strings = new HashSet<>();
    for (final Class<?> classType : classes) {
        for (final Field field : classType.getDeclaredFields()) {
            if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                    && field.getType().equals(String.class)) {
                try {
                    strings.add(String.valueOf(field.get(null)));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    //ignore
                }/*from w  w w.  java 2s.  co  m*/
            }
        }
    }
    return strings;
}

From source file:com.ocs.dynamo.utils.ClassUtils.java

/**
 * Check if the object has a (public) method that has the specified name
 * /*from  w ww.  j  ava2  s  . co m*/
 * @param obj
 * @param methodName
 * @return
 */
public static boolean hasMethod(Object obj, String methodName) {
    Method[] methods = obj.getClass().getMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName) && (Modifier.isPublic(method.getModifiers()))) {
            return true;
        }
    }
    return false;
}

From source file:org.jboss.dashboard.ui.config.components.factory.FactoryComponentFormatter.java

protected boolean isGetter(Method m) {
    if (m.getParameterTypes().length > 0)
        return false;
    Class returnType = m.getReturnType();
    if (returnType == null || returnType.equals(void.class))
        return false;
    int modifiers = m.getModifiers();
    if (!Modifier.isPublic(modifiers)) {
        return false;
    }/*  w  w  w  .  ja  va2s  .c o  m*/
    if (m.getName().startsWith("get") && !"get".equals(m.getName()) && !"getClass".equals(m.getName())) {
        return true;
    }
    if (m.getName().startsWith("is") && !"is".equals(m.getName()) && boolean.class.equals(returnType)) {
        return true;
    }
    return false;
}

From source file:ca.uhn.fhir.rest.server.RestfulServer.java

private int findResourceMethods(Object theProvider, Class<?> clazz) throws ConfigurationException {
    int count = 0;

    for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) {
        BaseMethodBinding<?> foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(),
                theProvider);//  w  ww.  java 2s .  co m
        if (foundMethodBinding == null) {
            continue;
        }

        count++;

        if (foundMethodBinding instanceof ConformanceMethodBinding) {
            myServerConformanceMethod = foundMethodBinding;
            continue;
        }

        if (!Modifier.isPublic(m.getModifiers())) {
            throw new ConfigurationException(
                    "Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public");
        } else {
            if (Modifier.isStatic(m.getModifiers())) {
                throw new ConfigurationException(
                        "Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static");
            } else {
                ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName());

                String resourceName = foundMethodBinding.getResourceName();
                ResourceBinding resourceBinding;
                if (resourceName == null) {
                    resourceBinding = myServerBinding;
                } else {
                    RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName);
                    if (myResourceNameToBinding.containsKey(definition.getName())) {
                        resourceBinding = myResourceNameToBinding.get(definition.getName());
                    } else {
                        resourceBinding = new ResourceBinding();
                        resourceBinding.setResourceName(resourceName);
                        myResourceNameToBinding.put(resourceName, resourceBinding);
                    }
                }

                List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations();
                if (allowableParams != null) {
                    for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) {
                        for (Annotation annotation : nextParamAnnotations) {
                            Package pack = annotation.annotationType().getPackage();
                            if (pack.equals(IdParam.class.getPackage())) {
                                if (!allowableParams.contains(annotation.annotationType())) {
                                    throw new ConfigurationException("Method[" + m.toString()
                                            + "] is not allowed to have a parameter annotated with "
                                            + annotation);
                                }
                            }
                        }
                    }
                }

                resourceBinding.addMethod(foundMethodBinding);
                ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName());
            }
        }
    }

    return count;
}

From source file:adalid.core.Operation.java

void initialiseFields(Class<?> clazz) {
    Class<?> c;/*from w w  w.j  a va2 s .  c  o  m*/
    int d, r;
    String name;
    Class<?> type;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = depth();
    int round = round();
    Class<?>[] classes = new Class<?>[] { Parameter.class, Expression.class };
    Class<?> dac = getClass();
    Class<?> top = Operation.class;
    int i = ArrayUtils.indexOf(classes, clazz);
    if (i != ArrayUtils.INDEX_NOT_FOUND) {
        c = classes[i];
        for (Field field : XS1.getFields(dac, top)) {
            field.setAccessible(true);
            logger.trace(field);
            name = field.getName();
            type = field.getType();
            if (!c.isAssignableFrom(type)) {
                continue;
            }
            modifiers = type.getModifiers();
            if (type.isInterface() && Expression.class.isAssignableFrom(type)) {
                restricted = false;
            } else {
                restricted = Modifier.isAbstract(modifiers);
            }
            restricted = restricted || !Modifier.isPublic(modifiers);
            if (restricted) {
                continue;
            }
            modifiers = field.getModifiers();
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            String errmsg = "failed to create a new instance of field \"" + field + "\" at " + this;
            try {
                o = field.get(this);
                if (o == null) {
                    logger.debug(message(type, name, o, depth, round));
                    o = XS1.initialiseField(this, field);
                    if (o == null) {
                        logger.debug(message(type, name, o, depth, round));
                        //                          throw new RuntimeException(message(type, name, o, depth, round));
                    } else {
                        logger.debug(message(type, name, o, depth, round));
                        field.set(this, o);
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new InstantiationRuntimeException(errmsg, ex);
            }
        }
    }
}

From source file:org.apache.axis2.jaxws.description.impl.EndpointInterfaceDescriptionImpl.java

private static Method[] getSEIMethods(Class sei) {
    // Per JSR-181 all methods on the SEI are mapped to operations regardless
    // of whether they include an @WebMethod annotation.  That annotation may
    // be present to customize the mapping, but is not required (p14)
    Method[] seiMethods = sei.getMethods();
    ArrayList methodList = new ArrayList();
    if (sei != null) {
        for (Method method : seiMethods) {

            if (method.getDeclaringClass().getName().equals("java.lang.Object")) {
                continue;
            }//from   w w  w .j a va  2  s.com
            methodList.add(method);
            if (!Modifier.isPublic(method.getModifiers())) {
                // JSR-181 says methods must be public (p14)
                throw ExceptionFactory.makeWebServiceException(Messages.getMessage("seiMethodsErr"));
            }
            // TODO: other validation per JSR-181
        }

    }
    return (Method[]) methodList.toArray(new Method[methodList.size()]);
    //        return seiMethods;
}

From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java

/**
 * @param field//from  ww w .  j a  v a  2s . co m
 * @param class1
 */
private <P> void doWithPropertySafe(PropertyMetadata<T, P> metadata)
        throws IllegalArgumentException, IllegalAccessException {

    AnnotatedElement[] accessors = metadata.getAccessors();

    if (this.findJaxbAnnotation(accessors, XmlTransient.class) != null)
        return;

    XmlSchemaType xmlSchemaType = this.findJaxbAnnotation(accessors, XmlSchemaType.class);
    // a pattern for property's class - force creating
    TypedPattern<P> pattern = null;
    if (xmlSchemaType != null) {
        // the schema type determines the pattern - if it is not present in the registry, it will be present after determining it on the basis of Java class
        // of the property
        QName typeName = new QName(xmlSchemaType.namespace(), xmlSchemaType.name());
        pattern = this.patternRegistry.findPatternByType(typeName, metadata.getPropertyClass());
        if (log.isTraceEnabled() && pattern != null)
            log.trace("-- @XmlSchemaType points to {}", pattern.toString());
    }

    if (pattern == null)
        pattern = this.patternRegistry.determineAndCacheXmlPattern(metadata.getPropertyClass());

    // is it value or list?
    XmlValue xmlValue = this.findJaxbAnnotation(accessors, XmlValue.class);
    XmlList xmlList = this.findJaxbAnnotation(accessors, XmlList.class);
    if (xmlValue != null || xmlList != null) {
        // the field's class must be a simpleType, i.e., a type convertible to String, which is either:
        //  - a type registered in org.javelin.sws.ext.bind.internal.BuiltInMappings.initialize()
        //  - a type which has only one property annotated with @XmlValue
        // a type with one @XmlValue property + non-zero @XmlAttribute properties is complex type with simple content, not a simple type
        if (!(pattern.isSimpleType() && pattern instanceof SimpleContentPattern))
            throw new RuntimeException("TODO: should be simpleType");

        if (log.isTraceEnabled())
            log.trace("-- @XmlValue property \"{}\" of type {} mapped to {}", metadata.getPropertyName(),
                    pattern.getJavaType().getName(), pattern.toString());

        metadata.setPattern(pattern);
        if (this.valueMetadata != null)
            throw new RuntimeException("TODO: Only one @XmlValue allowed!");

        this.valueMetadata = metadata;
        return;
    }

    // is it an attribute?
    XmlAttribute xmlAttribute = this.findJaxbAnnotation(accessors, XmlAttribute.class);
    if (xmlAttribute != null) {
        String namespace = XMLConstants.NULL_NS_URI;
        if (this.attributeFormDefault == XmlNsForm.QUALIFIED) {
            // the attribute MUST have namespace
            namespace = "##default".equals(xmlAttribute.namespace()) ? this.typeName.getNamespaceURI()
                    : xmlAttribute.namespace();
        } else {
            // the attribute MAY have namespace
            // TODO: handle org.javelin.sws.ext.bind.annotations.XmlAttribute
            if (!"##default".equals(xmlAttribute.namespace()))
                namespace = xmlAttribute.namespace();
        }
        String name = "##default".equals(xmlAttribute.name()) ? metadata.getPropertyName()
                : xmlAttribute.name();

        if (!(pattern.isSimpleType() && pattern instanceof SimpleContentPattern))
            throw new RuntimeException("TODO: should be simpleType");

        QName attributeQName = new QName(namespace, name);

        if (log.isTraceEnabled())
            log.trace("-- @XmlAttribute property \"{}\" of type {} mapped to {} attribute {}",
                    metadata.getPropertyName(), pattern.getJavaType().getName(), attributeQName,
                    pattern.toString());

        metadata.setPattern(
                AttributePattern.newAttributePattern(attributeQName, (SimpleContentPattern<P>) pattern));
        this.childAttributeMetadata.add(metadata);
        return;
    }

    // is it an element?
    XmlElement xmlElement = this.findJaxbAnnotation(accessors, XmlElement.class);

    // field is also an element when told so using XmlAccessorType
    boolean isElement = false;

    if (accessors[0] instanceof Field) {
        if (this.accessType == XmlAccessType.FIELD)
            isElement = true;
        else if (this.accessType == XmlAccessType.PUBLIC_MEMBER
                && Modifier.isPublic(((Field) accessors[0]).getModifiers()))
            isElement = true;
    } else if (accessors[0] instanceof Method) {
        if (this.accessType == XmlAccessType.PROPERTY)
            isElement = true;
        else if (this.accessType == XmlAccessType.PUBLIC_MEMBER
                && Modifier.isPublic(((Method) accessors[0]).getModifiers())) {
            // TODO: what if getter is private and setter is public?
            isElement = true;
        }
    }

    if (xmlElement != null || isElement) {
        String namespace = XMLConstants.NULL_NS_URI;
        if (this.elementFormDefault == XmlNsForm.QUALIFIED) {
            // the element MUST have namespace
            namespace = xmlElement == null || "##default".equals(xmlElement.namespace())
                    ? this.typeName.getNamespaceURI()
                    : xmlElement.namespace();
        } else {
            // the element MAY have namespace
            if (xmlElement != null && !"##default".equals(xmlElement.namespace()))
                namespace = xmlElement.namespace();
        }
        String name = xmlElement == null || "##default".equals(xmlElement.name()) ? metadata.getPropertyName()
                : xmlElement.name();
        QName elementQName = new QName(namespace, name);

        if (log.isTraceEnabled())
            log.trace("-- @XmlElement property \"{}\" of type {} mapped to {} element with {}",
                    metadata.getPropertyName(), pattern.getJavaType().getName(), elementQName,
                    pattern.toString());

        ElementPattern<?> elementPattern = ElementPattern.newElementPattern(elementQName, pattern);
        XmlElementWrapper xmlElementWrapper = this.findJaxbAnnotation(accessors, XmlElementWrapper.class);
        if (xmlElementWrapper != null) {
            if (!"##default".equals(xmlElementWrapper.namespace()))
                namespace = xmlElementWrapper.namespace();
            name = !"##default".equals(xmlElementWrapper.name()) ? xmlElementWrapper.name()
                    : metadata.getPropertyName();

            // XmlElementWrapper creates (in XSD Category) a new complex, anonymous, nested (inside element declaration) type
            // DESIGNFLAW: XmlElementWrapper works, but not as clean as it should
            PropertyMetadata<T, ?> md = PropertyMetadata.newPropertyMetadata(this.clazz,
                    metadata.getCollectionClass(), "", PropertyKind.PASSTHROUGH);
            md.setPattern(elementPattern);
            ComplexTypePattern<T> newAnonymousType = ComplexTypePattern.newContentModelPattern(null, this.clazz,
                    md);
            // TODO: Handle @XmlElementWrapper for collection properties
            // TODO: JAXB2 doesn't allow this, but maybe it's a good idea to be able to wrap non-collection properties also?
            // TODO: maybe it's a good idea to create @XmlElementWrappers class (aggregating multime @XmlElementWrapper annotations?)
            elementPattern = ElementPattern.newElementPattern(new QName(namespace, name), newAnonymousType);
            metadata.setWrappedCollection(true);
        }

        metadata.setPattern(elementPattern);
        this.childElementMetadata.add(metadata);
        return;
    }
}

From source file:com.duy.pascal.interperter.libraries.PascalLibraryManager.java

public void addMethodFromLibrary(Class<? extends IPascalLibrary> clazz, @Nullable Object instance,
        @Nullable LineNumber line) throws PermissionDeniedException {

    if (instance instanceof IAndroidLibrary && mHandler != null && mHandler.getApplicationContext() != null) {
        String[] permissions = ((IAndroidLibrary) instance).needPermission();
        for (String permission : permissions) {
            if (DLog.ANDROID) {
                int i = ActivityCompat.checkSelfPermission(mHandler.getApplicationContext(), permission);
                if (i != PackageManager.PERMISSION_GRANTED) {
                    throw new PermissionDeniedException(((IAndroidLibrary) instance).getName(), permission,
                            line);/*from   w ww  . ja va  2 s.com*/
                }
            }
        }
    }

    PascalLibrary library = (PascalLibrary) instance;
    if (library != null) {
        library.declareConstants(mProgram);
        library.declareFunctions(mProgram);
        library.declareTypes(mProgram);
        library.declareVariables(mProgram);
    }

    ArrayList<MethodDeclaration> declarations = METHOD_CACHE.get(clazz);
    if (declarations == null) {
        declarations = new ArrayList<>();
        for (Method method : clazz.getDeclaredMethods()) {
            if (Modifier.isPublic(method.getModifiers()) && !isHiddenSystemMethod(method.getName())) {
                if (AndroidLibraryUtils.getSdkVersion() >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    if (method.getAnnotation(PascalMethod.class) != null) {
                        PascalMethod annotation = method.getAnnotation(PascalMethod.class);
                        String description = annotation.description();
                        MethodDeclaration methodDecl = new MethodDeclaration(instance, method, description);
                        declarations.add(methodDecl);
                    }
                } else {
                    MethodDeclaration methodDeclaration = new MethodDeclaration(instance, method);
                    declarations.add(methodDeclaration);
                }
            }
        }
        Collections.sort(declarations, new Comparator<AbstractFunction>() {
            @Override
            public int compare(AbstractFunction o1, AbstractFunction o2) {
                if (o1.getName().equals(o2.getName())) {
                    ArgumentType[] types1 = o1.argumentTypes();
                    ArgumentType[] types2 = o2.argumentTypes();
                    if (types1.length != types2.length) {
                        return -1;
                    }

                    for (int i = 0; i < types1.length; i++) {
                        Class<?> t1Class = types1[i].getRuntimeClass();
                        Class<?> t2Class = types2[i].getRuntimeClass();
                        if (t1Class.equals(t2Class)) {
                            continue;
                        }

                        if (TypeConverter.isPrimitive(t1Class) && TypeConverter.isPrimitive(t2Class)) {
                            if (!types1[i].equals(types2[i])) {
                                if (TypeConverter.isLowerThanPrecedence(t1Class, t2Class)) {
                                    return -1;
                                }
                            }
                        } else {
                            return -1;
                        }
                    }
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
        METHOD_CACHE.put(clazz, declarations);
    } else {
        for (MethodDeclaration declaration : declarations) {
            declaration.setInstance(instance);
        }
    }
    for (AbstractFunction declaration : declarations) {
        mProgram.declareFunction(declaration);
    }
}

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  w  w  w  .  jav  a 2  s  . c  o m*/
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:adalid.core.EntityAtlas.java

@SuppressWarnings("deprecation")
void initialiseFields(Class<?> clazz) {
    track("initialiseFields", _declaringArtifact, clazz.getSimpleName());
    Class<?> c;//from   ww w.  j  av  a  2  s .c o  m
    int d, r;
    String name;
    String key;
    String pattern = "there are several fields for operation {0}";
    String message;
    Class<?> type;
    Class<?> decl;
    Class<?> operationClass;
    Field operationField;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = _declaringArtifact.depth();
    int round = _declaringArtifact.round();
    Class<?>[] classes = new Class<?>[] { Property.class, Key.class, Tab.class, View.class, Instance.class,
            NamedValue.class, Expression.class, Transition.class, Operation.class, Trigger.class };
    Class<?> dac = _declaringArtifact.getClass();
    Class<?> top = Entity.class;
    int i = ArrayUtils.indexOf(classes, clazz);
    if (i != ArrayUtils.INDEX_NOT_FOUND) {
        c = classes[i];
        for (Field field : XS1.getFields(dac, top)) {
            field.setAccessible(true);
            logger.trace(field);
            name = field.getName();
            type = field.getType();
            decl = field.getDeclaringClass();
            if (!c.isAssignableFrom(type)) {
                continue;
            }
            if (c.equals(Expression.class) && Property.class.isAssignableFrom(type)) {
                continue;
            }
            // TODO: extension handling
            if (field.isAnnotationPresent(Extension.class) && Entity.class.isAssignableFrom(type)) {
                //                  if (!dac.equals(decl) || !dac.isAssignableFrom(type)) {
                //                      continue;
                //                  }
                continue;
            }
            modifiers = type.getModifiers();
            if (NamedValue.class.isAssignableFrom(type) || Expression.class.isAssignableFrom(type)) {
                restricted = false;
            } else {
                restricted = type.isInterface() || Modifier.isAbstract(modifiers);
            }
            restricted = restricted || !Modifier.isPublic(modifiers);
            if (restricted) {
                continue;
            }
            modifiers = field.getModifiers();
            restricted = Modifier.isPrivate(modifiers);
            if (restricted) {
                continue;
            }
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            if (Operation.class.isAssignableFrom(type)) {
                key = type.getSimpleName();
                operationClass = _operationClasses.get(key);
                if (operationClass != null) {
                    operationField = _operationFields.get(key);
                    if (operationField == null) {
                        _operationFields.put(key, field);
                    } else {
                        message = MessageFormat.format(pattern, operationClass.getName());
                        logger.warn(message);
                        TLC.getProject().getParser().increaseWarningCount();
                    }
                }
            }
            String errmsg = "failed to create a new instance of field \"" + field + "\" at "
                    + _declaringArtifact;
            try {
                o = field.get(_declaringArtifact);
                if (o == null) {
                    logger.debug(message(type, name, o, depth, round));
                    o = XS1.initialiseField(_declaringArtifact, field);
                    if (o == null) {
                        logger.debug(message(type, name, o, depth, round));
                        //                          throw new RuntimeException(message(type, name, o, depth, round));
                    } else {
                        logger.debug(message(type, name, o, depth, round));
                        field.set(_declaringArtifact, o);
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new InstantiationRuntimeException(errmsg, ex);
            }
        }
    }
}