Example usage for java.lang.reflect Method getModifiers

List of usage examples for java.lang.reflect Method getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Method getModifiers.

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:org.cruxframework.crux.core.server.rest.core.registry.ResourceRegistry.java

/**
 * //from   ww  w. j  av  a2 s.com
 * @param base
 * @param clazz
 * @param method
 * @param restMethodNames 
 */
protected RestMethodRegistrationInfo processMethod(String base, Class<?> clazz, Method method,
        Set<String> restMethodNames) {
    if (method != null) {
        Path path = method.getAnnotation(Path.class);
        String httpMethod = null;
        try {
            httpMethod = HttpMethodHelper.getHttpMethod(method.getAnnotations());
        } catch (InvalidRestMethod e) {
            logger.error(
                    "Invalid Method: " + method.getDeclaringClass().getName() + "." + method.getName() + "().",
                    e);
        }

        boolean pathPresent = path != null;
        boolean restAnnotationPresent = pathPresent || (httpMethod != null);

        UriBuilder builder = new UriBuilder();
        if (base != null)
            builder.path(base);
        if (clazz.isAnnotationPresent(Path.class)) {
            builder.path(clazz);
        }
        if (path != null) {
            builder.path(method);
        }
        String pathExpression = builder.getPath();
        if (pathExpression == null) {
            pathExpression = "";
        }
        if (restAnnotationPresent && !Modifier.isPublic(method.getModifiers())) {
            logger.error("Rest annotations found at non-public method: " + method.getDeclaringClass().getName()
                    + "." + method.getName() + "(); Only public methods may be exposed as resource methods.");
        } else if (httpMethod != null) {
            if (restMethodNames.contains(method.getName())) {
                logger.error("Overloaded rest method: " + method.getDeclaringClass().getName() + "."
                        + method.getName() + " found. It is not supported for Crux REST services.");
            } else {
                ResourceMethod invoker = new ResourceMethod(clazz, method, httpMethod);
                rootSegment.addPath(pathExpression, invoker);
                restMethodNames.add(method.getName());
                size++;
                return new RestMethodRegistrationInfo(pathExpression, invoker);
            }
        } else {
            if (restAnnotationPresent) {
                logger.error("Method: " + method.getDeclaringClass().getName() + "." + method.getName()
                        + "() declares rest annotations, but it does not inform the methods it must handle. Use one of @PUT, @POST, @GET or @DELETE.");
            } else if (logger.isDebugEnabled()) {
                logger.debug("Method: " + method.getDeclaringClass().getName() + "." + method.getName()
                        + "() ignored. It is not a rest method.");
            }
        }
    }
    return null;
}

From source file:com.xie.javacase.json.JSONObject.java

private void populateInternalMap(Object bean, boolean includeSuperClass) {
    Class klass = bean.getClass();

    /* If klass.getSuperClass is System class then force includeSuperClass to false. */

    if (klass.getClassLoader() == null) {
        includeSuperClass = false;//from  ww  w .  j  a va2  s  . co m
    }

    Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
        try {
            Method method = methods[i];
            if (Modifier.isPublic(method.getModifiers())) {
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")) {
                    key = name.substring(3);
                } else if (name.startsWith("is")) {
                    key = name.substring(2);
                }
                if (key.length() > 0 && Character.isUpperCase(key.charAt(0))
                        && method.getParameterTypes().length == 0) {
                    if (key.length() == 1) {
                        key = key.toLowerCase();
                    } else if (!Character.isUpperCase(key.charAt(1))) {
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                    }

                    Object result = method.invoke(bean, (Object[]) null);
                    if (result == null) {
                        map.put(key, NULL);
                    } else if (result.getClass().isArray()) {
                        map.put(key, new JSONArray(result, includeSuperClass));
                    } else if (result instanceof Collection) { // List or Set
                        map.put(key, new JSONArray((Collection) result, includeSuperClass));
                    } else if (result instanceof Map) {
                        map.put(key, new JSONObject((Map) result, includeSuperClass));
                    } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper
                        map.put(key, result);
                    } else {
                        if (result.getClass().getPackage().getName().startsWith("java")
                                || result.getClass().getClassLoader() == null) {
                            map.put(key, result.toString());
                        } else { // User defined Objects
                            map.put(key, new JSONObject(result, includeSuperClass));
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.jaffa.transaction.services.TransactionConsumer.java

/**
 * Invokes the handler to process the payload.
 *//*w ww .j  a v  a 2s  . c  om*/
protected void invokeHandler(UOW uow, TransactionInfo transactionInfo, Object dataBean) throws Exception {
    // Obtain the handlerClass
    Class handlerClass = Class.forName(transactionInfo.getToClass());

    // Obtain the handler method
    Method handlerMethod = null;
    try {
        handlerMethod = handlerClass.getMethod(transactionInfo.getToMethod(),
                new Class[] { UOW.class, dataBean.getClass() });
    } catch (NoSuchMethodException e) {
        // Note that the payload could be a subclass of the argument that the handler method expects
        // Hence use the dataBeanClass specified in the transactionInfo to get the appropriate handlerMethod
        if (log.isDebugEnabled()) {
            log.debug("Handler method " + transactionInfo.getToClass() + '.' + transactionInfo.getToMethod()
                    + "(UOW, " + dataBean.getClass().getName() + ')'
                    + " not found. Will look for a method that takes " + transactionInfo.getDataBean()
                    + " as argument");
        }
        Class dataBeanClass = Class.forName(transactionInfo.getDataBean());
        handlerMethod = handlerClass.getMethod(transactionInfo.getToMethod(),
                new Class[] { UOW.class, dataBeanClass });
    }

    // Create an instance of handlerClass, if the handlerMethod is not static
    Object handlerObject = Modifier.isStatic(handlerMethod.getModifiers()) ? null : handlerClass.newInstance();

    // Invoke the handler
    if (log.isDebugEnabled()) {
        log.debug("Invoking the handler " + handlerMethod);
    }
    handlerMethod.invoke(handlerObject, new Object[] { uow, dataBean });
}

From source file:org.apache.axis.description.JavaServiceDesc.java

/**
 * Fill in a service description by introspecting the implementation
 * class.//from w  w  w .j av  a  2s. c  o  m
 */
public void loadServiceDescByIntrospection(Class implClass) {
    if (introspectionComplete || implClass == null) {
        return;
    }

    // set the implementation class for the service description
    this.implClass = implClass;
    if (Skeleton.class.isAssignableFrom(implClass)) {
        isSkeletonClass = true;
        loadSkeletonOperations();
    }

    /** If the class knows what it should be exporting,
    * respect its wishes.
    */
    AxisServiceConfig axisConfig = null;
    try {
        Method method = implClass.getDeclaredMethod("getAxisServiceConfig", new Class[] {});
        if (method != null && Modifier.isStatic(method.getModifiers())) {
            axisConfig = (AxisServiceConfig) method.invoke(null, null);
        }
    } catch (Exception e) {
        // No problem, just continue without...
    }

    if (axisConfig != null) {
        String allowedMethodsStr = axisConfig.getAllowedMethods();
        if (allowedMethodsStr != null && !"*".equals(allowedMethodsStr)) {
            ArrayList methodList = new ArrayList();
            StringTokenizer tokenizer = new StringTokenizer(allowedMethodsStr, " ,");
            while (tokenizer.hasMoreTokens()) {
                methodList.add(tokenizer.nextToken());
            }
            setAllowedMethods(methodList);
        }
    }

    loadServiceDescByIntrospectionRecursive(implClass);

    // All operations should now be synchronized.  Check it.
    for (Iterator iterator = operations.iterator(); iterator.hasNext();) {
        OperationDesc operation = (OperationDesc) iterator.next();
        if (operation.getMethod() == null) {
            throw new InternalException(Messages.getMessage("badWSDDOperation", operation.getName(),
                    "" + operation.getNumParams()));
        }
    }

    if ((style == Style.MESSAGE) && operations.size() == 1) {
        messageServiceDefaultOp = (OperationDesc) operations.get(0);
    }

    introspectionComplete = true;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static String getCppDeclaration(Method m, Class<?> relClass) {
    return getCppModifiers(m.getModifiers()) + getCppType(m.getReturnType(), relClass) + " " + fixMethodName(m)
            + getCppParamDeclarations(m.getParameterTypes(), relClass) + ";";
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static String getNativeMethodCppDeclaration(Method m, Class<?> relClass) {
    return getCppModifiers(m.getModifiers()) + getCppType(m.getReturnType(), relClass) + " " + fixMethodName(m)
            + "Native" + getCppParamDeclarations(m.getParameterTypes(), relClass) + ";";
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean isMethodToMakeEasy(Method m) {
    if (Modifier.isStatic(m.getModifiers())) {
        return false;
    }/*ww  w.  ja v a  2 s .co m*/
    Class<?> types[] = m.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        Class<?> type = types[i];
        if (type.isArray() && !type.getComponentType().isPrimitive()) {
            return false;
        }
    }
    for (int i = 0; i < types.length; i++) {
        Class<?> type = types[i];
        if (type.isArray() || isString(type)) {
            return true;
        }
    }
    return false;
    //        return !Modifier.isStatic(m.getModifiers())
    //                && Arrays.stream(m.getParameterTypes())
    //                .anyMatch(t -> t.isArray() || isString(t))
    //                && Arrays.stream(m.getParameterTypes())
    //                .noneMatch(t -> t.isArray() && !t.getComponentType().isPrimitive());
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static String getEasyCallCppDeclaration(Method m, Class<?> relClass) {
    return getCppModifiers(m.getModifiers()) + getCppType(m.getReturnType(), relClass) + " " + fixMethodName(m)
            + getEasyCallCppParamDeclarations(m.getParameterTypes(), relClass) + ";";
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Finds the getter method from the declaring class suitable to get a
 * reference to the field.//from   w w w . j ava  2s  . c  o  m
 *
 * @author paouelle
 *
 * @param  declaringClass the non-<code>null</code> class declaring the field
 * @param  prefix the non-<code>null</code> getter prefix to use
 * @return the getter method for the field or <code>null</code> if none found
 * @throws IllegalArgumentException if unable to find a suitable getter
 */
private Method findGetterMethod(Class<?> declaringClass, String prefix) {
    final String mname = prefix + WordUtils.capitalize(name, '_', '-');

    try {
        final Method m = declaringClass.getDeclaredMethod(mname);
        final int mods = m.getModifiers();

        if (Modifier.isAbstract(mods) || Modifier.isStatic(mods)) {
            return null;
        }
        final Class<?> wtype = ClassUtils.primitiveToWrapper(type);
        final Class<?> wrtype = ClassUtils.primitiveToWrapper(
                DataTypeImpl.unwrapOptionalIfPresent(m.getReturnType(), m.getGenericReturnType()));

        org.apache.commons.lang3.Validate.isTrue(wtype.isAssignableFrom(wrtype),
                "expecting getter for field '%s' with return type: %s", field, type.getName());
        m.setAccessible(true);
        return m;
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Finds the setter method from the declaring class suitable to set a
 * value for the field./*ww w .j a  v a 2  s  . com*/
 *
 * @author paouelle
 *
 * @param  declaringClass the non-<code>null</code> class declaring the field
 * @return the setter method for the field or <code>null</code> if none found
 * @throws IllegalArgumentException if unable to find a suitable setter
 */
private Method findSetterMethod(Class<?> declaringClass) {
    final String mname = "set" + WordUtils.capitalize(name, '_', '-');

    try {
        final Method m = declaringClass.getDeclaredMethod(mname, type);
        final int mods = m.getModifiers();

        if (Modifier.isAbstract(mods) || Modifier.isStatic(mods)) {
            return null;
        }
        org.apache.commons.lang3.Validate.isTrue(m.getParameterCount() == 1,
                "expecting setter for field '%s' with one parameter", field);
        final Class<?> wtype = ClassUtils.primitiveToWrapper(type);
        final Class<?> wptype = ClassUtils.primitiveToWrapper(DataTypeImpl.unwrapOptionalIfPresent(
                m.getParameterTypes()[0], m.getParameters()[0].getParameterizedType()));

        org.apache.commons.lang3.Validate.isTrue(wtype.isAssignableFrom(wptype),
                "expecting setter for field '%s' with parameter type: %s", field, type.getName());
        m.setAccessible(true);
        return m;
    } catch (NoSuchMethodException e) {
        return null;
    }
}