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.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  .  ja  v a2s . 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:objenome.util.bytecode.SgUtils.java

private static void checkModifiers(int type, int modifiers) {
    for (int modifier = ABSTRACT; modifier <= STRICTFP; modifier++) {
        if (Modifier.isPrivate(modifiers) && !MODIFIERS_MATRIX[PRIVATE][type]) {
            throwIllegalArgument(type, PRIVATE);
        }//from   www .  ja va2 s.  c o  m
        if (Modifier.isProtected(modifiers) && !MODIFIERS_MATRIX[PROTECTED][type]) {
            throwIllegalArgument(type, PROTECTED);
        }
        if (Modifier.isPublic(modifiers) && !MODIFIERS_MATRIX[PUBLIC][type]) {
            throwIllegalArgument(type, PUBLIC);
        }
        if (Modifier.isStatic(modifiers) && !MODIFIERS_MATRIX[STATIC][type]) {
            throwIllegalArgument(type, STATIC);
        }
        if (Modifier.isAbstract(modifiers) && !MODIFIERS_MATRIX[ABSTRACT][type]) {
            throwIllegalArgument(type, ABSTRACT);
        }
        if (Modifier.isFinal(modifiers) && !MODIFIERS_MATRIX[FINAL][type]) {
            throwIllegalArgument(type, FINAL);
        }
        if (Modifier.isNative(modifiers) && !MODIFIERS_MATRIX[NATIVE][type]) {
            throwIllegalArgument(type, NATIVE);
        }
        if (Modifier.isSynchronized(modifiers) && !MODIFIERS_MATRIX[SYNCHRONIZED][type]) {
            throwIllegalArgument(type, SYNCHRONIZED);
        }
        if (Modifier.isTransient(modifiers) && !MODIFIERS_MATRIX[TRANSIENT][type]) {
            throwIllegalArgument(type, TRANSIENT);
        }
        if (Modifier.isVolatile(modifiers) && !MODIFIERS_MATRIX[VOLATILE][type]) {
            throwIllegalArgument(type, VOLATILE);
        }
        if (Modifier.isStrict(modifiers) && !MODIFIERS_MATRIX[STRICTFP][type]) {
            throwIllegalArgument(type, STRICTFP);
        }
    }
}

From source file:org.apache.axis2.description.java2wsdl.DocLitBareSchemaGenerator.java

@Override
protected Method[] processMethods(Method[] declaredMethods) throws Exception {
    ArrayList<Method> list = new ArrayList<Method>();
    //short the elements in the array
    Arrays.sort(declaredMethods, new MathodComparator());

    // since we do not support overload
    HashMap<String, Method> uniqueMethods = new LinkedHashMap<String, Method>();
    XmlSchemaComplexType methodSchemaType;
    XmlSchemaSequence sequence;/*from   ww w . j  ava  2  s. c  om*/

    for (Method jMethod : declaredMethods) {
        if (jMethod.isBridge()) {
            continue;
        }
        WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod);
        if (methodAnnon != null) {
            if (methodAnnon.isExclude()) {
                continue;
            }
        }
        String methodName = jMethod.getName();
        // no need to think abt this method , since that is system
        // config method
        if (excludeMethods.contains(methodName)) {
            continue;
        }

        if (uniqueMethods.get(methodName) != null) {
            log.warn("We don't support method overloading. Ignoring [" + methodName + "]");
            continue;
        }

        if (!Modifier.isPublic(jMethod.getModifiers())) {
            // no need to generate Schema for non public methods
            continue;
        }

        boolean addToService = false;
        AxisOperation axisOperation = service.getOperation(new QName(methodName));
        if (axisOperation == null) {
            axisOperation = Utils.getAxisOperationForJmethod(jMethod);
            if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(axisOperation.getMessageExchangePattern())) {
                AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                if (outMessage != null) {
                    outMessage.setName(methodName + RESULT);
                }
            }
            addToService = true;
        }

        // Maintain a list of methods we actually work with
        list.add(jMethod);
        processException(jMethod, axisOperation);
        uniqueMethods.put(methodName, jMethod);
        //create the schema type for the method wrapper

        uniqueMethods.put(methodName, jMethod);
        Class<?>[] paras = jMethod.getParameterTypes();
        String parameterNames[] = methodTable.getParameterNames(methodName);
        AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        if (inMessage != null) {
            inMessage.setName(methodName + "RequestMessage");
        }
        Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations();
        if (paras.length > 1) {
            sequence = new XmlSchemaSequence();
            methodSchemaType = createSchemaTypeForMethodPart(methodName);
            methodSchemaType.setParticle(sequence);
            inMessage.setElementQName(typeTable.getQNamefortheType(methodName));
            service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);
            inMessage.setPartName(methodName);
            for (int j = 0; j < paras.length; j++) {
                Class<?> methodParameter = paras[j];
                String parameterName = getParameterName(parameterAnnotation, j, parameterNames);
                if (generateRequestSchema(methodParameter, parameterName, jMethod, sequence)) {
                    break;
                }
            }
        } else if (paras.length == 1) {
            if (paras[0].isArray()) {
                sequence = new XmlSchemaSequence();

                methodSchemaType = createSchemaTypeForMethodPart(methodName);
                methodSchemaType.setParticle(sequence);
                Class<?> methodParameter = paras[0];
                inMessage.setElementQName(typeTable.getQNamefortheType(methodName));
                service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);
                inMessage.setPartName(methodName);
                String parameterName = getParameterName(parameterAnnotation, 0, parameterNames);
                if (generateRequestSchema(methodParameter, parameterName, jMethod, sequence)) {
                    break;
                }
            } else {
                String parameterName = getParameterName(parameterAnnotation, 0, parameterNames);
                Class<?> methodParameter = paras[0];
                Method processMethod = processedParameters.get(parameterName);
                if (processMethod != null) {
                    throw new AxisFault(
                            "Inavalid Java class," + " there are two methods [" + processMethod.getName()
                                    + " and " + jMethod.getName() + " ]which have the same parameter names");
                } else {
                    processedParameters.put(parameterName, jMethod);
                    generateSchemaForType(null, methodParameter, parameterName);
                    inMessage.setElementQName(typeTable.getQNamefortheType(parameterName));
                    inMessage.setPartName(parameterName);
                    inMessage.setWrapped(false);
                    service.addMessageElementQNameToOperationMapping(
                            typeTable.getQNamefortheType(parameterName), axisOperation);
                }
            }
        }

        // for its return type
        Class<?> returnType = jMethod.getReturnType();

        if (!"void".equals(jMethod.getReturnType().getName())) {
            AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
            if (returnType.isArray()) {
                methodSchemaType = createSchemaTypeForMethodPart(jMethod.getName() + RESULT);
                sequence = new XmlSchemaSequence();
                methodSchemaType.setParticle(sequence);
                WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod);
                String returnName = "return";
                if (returnAnnon != null) {
                    returnName = returnAnnon.getName();
                    if (returnName != null && !"".equals(returnName)) {
                        returnName = "return";
                    }
                }
                if (nonRpcMethods.contains(methodName)) {
                    generateSchemaForType(sequence, null, returnName);
                } else {
                    generateSchemaForType(sequence, returnType, returnName);
                }
            } else {
                generateSchemaForType(null, returnType, methodName + RESULT);
                outMessage.setWrapped(false);
            }
            outMessage.setElementQName(typeTable.getQNamefortheType(methodName + RESULT));
            outMessage.setName(methodName + "ResponseMessage");
            outMessage.setPartName(methodName + RESULT);
            service.addMessageElementQNameToOperationMapping(typeTable.getQNamefortheType(methodName + RESULT),
                    axisOperation);
        }
        if (addToService) {
            service.addOperation(axisOperation);
        }
    }
    return list.toArray(new Method[list.size()]);
}

From source file:com.basistech.rosette.apimodel.ModelTest.java

@Test
public void packageTest() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException,
        InstantiationException, IOException {
    Reflections reflections = new Reflections(this.getClass().getPackage().getName(),
            new SubTypesScanner(false));

    Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
    for (Object clazz : allClasses) {
        String className = ((Class) clazz).getName();
        if (className.contains("com.basistech.rosette.dm")) {
            continue;
        }//w w w.j a  v  a2s .c o m
        if (className.contains("Adm")) {
            continue; // these are too hard.
        }
        if (className.endsWith(".ModelTest")) {
            continue;
        }
        if (className.endsWith(".NonNullTest")) {
            continue;
        }
        if (className.endsWith("Mixin")) {
            continue;
        }

        if (className.endsWith("Builder")) {
            continue;
        }
        if (className.contains(".batch.")) {
            // there are polymorphism issues in here for this test strategy.
            continue;
        }

        Class c = Class.forName(className);
        if (Modifier.isAbstract(c.getModifiers())) {
            continue;
        }
        Constructor[] ctors = c.getDeclaredConstructors();
        if (ctors.length == 0) {
            continue;
        }
        Constructor ctor = ctors[0];
        if (ctor.getParameterTypes().length == 0) {
            continue; // don't want empty constructor
        }
        Object o1;
        if (Modifier.isPublic(ctor.getModifiers())) {

            boolean oldInputStreams = inputStreams;
            try {
                if (className.endsWith("ConstantsResponse")) {
                    inputStreams = false; // special case due to Object in there.
                }
                o1 = createObject(ctor);
            } finally {
                inputStreams = oldInputStreams;
            }

            // serialize
            // for a request, we might need a view
            ObjectWriter writer = mapper.writerWithView(Object.class);
            if (o1 instanceof DocumentRequest) {
                DocumentRequest r = (DocumentRequest) o1;
                if (r.getRawContent() instanceof String) {
                    writer = mapper.writerWithView(DocumentRequestMixin.Views.Content.class);
                }
            }
            String json = writer.writeValueAsString(o1);
            // deserialize
            Object o2 = mapper.readValue(json, (Class<? extends Object>) clazz);
            // verify
            assertEquals(o1, o2);
        }
    }
}

From source file:no.abmu.util.reflection.FieldUtil.java

public static Object getFieldValue(Object obj, String fieldName) {
    Assert.checkRequiredArgument("obj", obj);
    Assert.checkRequiredArgument("fieldName", fieldName);
    String errorMessage = "Object '" + obj.getClass().getName() + " does not have field/variable with name '"
            + fieldName + "'";
    Assert.assertTrue(errorMessage, hasObjectVariable(obj, fieldName));

    Field field = getField(obj, fieldName);

    Object value = null;/*w ww  .  j  a  v a 2 s  .c  om*/
    try {
        if (Modifier.isPublic(field.getModifiers())) {
            value = field.get(obj);
        } else {
            field.setAccessible(true);
            value = field.get(obj);
            field.setAccessible(false);
        }
    } catch (IllegalAccessException e) {
        logger.error(e.getMessage());
    }

    return value;
}

From source file:io.github.huherto.springyRecords.RecordMapper.java

/**
 * Initialize the mapping metadata for the given class.
 * @param mappedClass the mapped class./*from  ww w.  ja v  a  2 s  .com*/
 */
protected void initialize(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
    this.mappedFields = new HashMap<String, Field>();

    Field fields[] = mappedClass.getFields();
    for (Field field : fields) {
        int mod = field.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
            for (Annotation a : field.getAnnotations()) {
                if (a.annotationType().isAssignableFrom(Column.class)) {
                    Column c = (Column) a;
                    String columnName = c.name();
                    mappedFields.put(columnName, field);
                }
            }
        }
    }
}

From source file:org.codehaus.griffon.commons.ClassPropertyFetcher.java

private void init() {
    FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            if (field.isSynthetic())
                return;
            final int modifiers = field.getModifiers();
            if (!Modifier.isPublic(modifiers))
                return;

            final String name = field.getName();
            if (name.indexOf('$') == -1) {
                boolean staticField = Modifier.isStatic(modifiers);
                if (staticField) {
                    staticFetchers.put(name, new FieldReaderFetcher(field, staticField));
                } else {
                    instanceFetchers.put(name, new FieldReaderFetcher(field, staticField));
                }/*  w w w. j  a  v  a  2 s .c o m*/
            }
        }
    };

    MethodCallback methodCallback = new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            if (method.isSynthetic())
                return;
            if (!Modifier.isPublic(method.getModifiers()))
                return;
            if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) {
                if (method.getParameterTypes().length == 0) {
                    String name = method.getName();
                    if (name.indexOf('$') == -1) {
                        if (name.length() > 3 && name.startsWith("get")
                                && Character.isUpperCase(name.charAt(3))) {
                            name = name.substring(3);
                        } else if (name.length() > 2 && name.startsWith("is")
                                && Character.isUpperCase(name.charAt(2))
                                && (method.getReturnType() == Boolean.class
                                        || method.getReturnType() == boolean.class)) {
                            name = name.substring(2);
                        }
                        PropertyFetcher fetcher = new GetterPropertyFetcher(method, true);
                        staticFetchers.put(name, fetcher);
                        staticFetchers.put(StringUtils.uncapitalize(name), fetcher);
                    }
                }
            }
        }
    };

    List<Class<?>> allClasses = resolveAllClasses(clazz);
    for (Class<?> c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            try {
                fieldCallback.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            try {
                methodCallback.doWith(method);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
            }
        }
    }

    propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor desc : propertyDescriptors) {
        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            }
        }
    }
}

From source file:ColorUtils.java

private static boolean isConstantColorField(Field field) {
    return Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
            && Color.class == field.getType();
}

From source file:com.agileapes.couteau.context.spring.event.impl.GenericTranslationScheme.java

@Override
public void fillIn(Event originalEvent, ApplicationEvent translated) throws EventTranslationException {
    if (!(translated instanceof GenericApplicationEvent)) {
        return;/*from  w  ww.  j  av  a 2 s.c om*/
    }
    GenericApplicationEvent applicationEvent = (GenericApplicationEvent) translated;
    final Enumeration<?> propertyNames = applicationEvent.getPropertyNames();
    while (propertyNames.hasMoreElements()) {
        final String property = (String) propertyNames.nextElement();
        final Object value = applicationEvent.getProperty(property);
        final Method method = ReflectionUtils.findMethod(originalEvent.getClass(),
                "set" + StringUtils.capitalize(property));
        if (method == null || !Modifier.isPublic(method.getModifiers())
                || method.getParameterTypes().length != 1 || !method.getReturnType().equals(void.class)
                || !method.getParameterTypes()[0].isInstance(value)) {
            continue;
        }
        try {
            method.invoke(originalEvent, value);
        } catch (Exception e) {
            throw new EventTranslationException("Failed to call setter on original event", e);
        }
    }
}