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:java2typescript.jaxrs.ServiceDescriptorGenerator.java

/**
 * Main method to generate a REST Service desciptor out of JAX-RS service
 * class/*ww w  .j av  a 2  s  . c o m*/
 */
private Collection<RestService> generateRestServices(Collection<? extends Class<?>> classes) {

    List<RestService> services = new ArrayList<RestService>();

    for (Class<?> clazz : classes) {

        RestService service = new RestService();
        service.setName(clazz.getSimpleName());

        Path pathAnnotation = clazz.getAnnotation(Path.class);

        if (pathAnnotation == null) {
            throw new RuntimeException("No @Path on class " + clazz.getName());
        }

        service.setPath(pathAnnotation.value());

        for (Method method : clazz.getDeclaredMethods()) {
            if (Modifier.isPublic(method.getModifiers())) {
                RestMethod restMethod = generateMethod(method);
                service.getMethods().put(restMethod.getName(), restMethod);
            }
        }

        if (extras != null) {
            service.setExtra(extras.getExtraForService(clazz));
        }

        services.add(service);
    }
    return services;
}

From source file:org.apache.camel.maven.JavadocApiMethodGeneratorMojo.java

private String getResultType(Class<?> aClass, String name, String[] types) throws MojoExecutionException {
    Class<?>[] argTypes = new Class<?>[types.length];
    final ClassLoader classLoader = getProjectClassLoader();
    for (int i = 0; i < types.length; i++) {
        try {/* w w  w .  j av  a2 s  .  c  o  m*/
            try {
                argTypes[i] = ApiMethodParser.forName(types[i], classLoader);
            } catch (ClassNotFoundException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        } catch (IllegalArgumentException e) {
            throw new MojoExecutionException(e.getCause().getMessage(), e.getCause());
        }
    }

    // return null for non-public methods, and for non-static methods if includeStaticMethods is null or false
    String result = null;
    try {
        final Method method = aClass.getMethod(name, argTypes);
        int modifiers = method.getModifiers();
        if (!Modifier.isStatic(modifiers) || Boolean.TRUE.equals(includeStaticMethods)) {
            result = method.getReturnType().getCanonicalName();
        }
    } catch (NoSuchMethodException e) {
        // could be a non-public method
        try {
            aClass.getDeclaredMethod(name, argTypes);
        } catch (NoSuchMethodException e1) {
            throw new MojoExecutionException(e1.getMessage(), e1);
        }
    }

    return result;
}

From source file:org.gradle.api.internal.project.AnnotationProcessingTaskFactory.java

private void attachTaskAction(final Method method, Collection<Action<Task>> actions) {
    if (method.getAnnotation(TaskAction.class) == null) {
        return;//from www. j av a  2  s . co m
    }
    if (Modifier.isStatic(method.getModifiers())) {
        throw new GradleException(String.format("Cannot use @TaskAction annotation on static method %s.%s().",
                method.getDeclaringClass().getSimpleName(), method.getName()));
    }
    if (method.getParameterTypes().length > 0) {
        throw new GradleException(String.format(
                "Cannot use @TaskAction annotation on method %s.%s() as this method takes parameters.",
                method.getDeclaringClass().getSimpleName(), method.getName()));
    }
    actions.add(new Action<Task>() {
        public void execute(Task task) {
            ReflectionUtil.invoke(task, method.getName(), new Object[0]);
        }
    });
}

From source file:com.founder.e5.config.ConfigReader.java

/**
 * /*w  w  w .  j  a v  a 2 s. c o m*/
 * configcontext
 */
private void initRestart() throws Exception {
    InfoRestart[] infos = (InfoRestart[]) listRestart.toArray(new InfoRestart[0]);
    if (infos == null)
        return;
    //Restart init
    for (int i = 0; i < infos.length; i++) {
        Class myClass = Class.forName(infos[i].getInvokeClass());
        Method method = myClass.getMethod(infos[i].getInvokeMethod(), null);
        if (Modifier.isStatic(method.getModifiers()))
            method.invoke(null, null);
        else
            method.invoke(myClass.newInstance(), null);
    }
    //DBSession Init
    for (int i = 0; i < listDBSession.size(); i++) {
        InfoDBSession db = (InfoDBSession) getDBSessions().get(i);
        DBSessionFactory.registerDB(db.getName(), db.getImplementation());
    }
    //ID Init
    for (int i = 0; i < listID.size(); i++) {
        InfoID id = (InfoID) getIDs().get(i);
        EUID.registerID(id.getName(), id.getType(), id.getParam());
    }
}

From source file:grails.plugin.cache.GrailsAnnotationCacheOperationSource.java

protected Collection<CacheOperation> computeCacheOperations(Method method, Class<?> targetClass) {
    // Don't allow no-public methods as required.
    if (publicMethodsOnly && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }//from w  ww. j  a  v  a2 s  . c o m

    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    // If we are dealing with method with generic parameters, find the original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // First try is the method in the target class.
    Collection<CacheOperation> opDef = findCacheOperations(specificMethod);
    if (opDef != null) {
        return opDef;
    }

    // Second try is the caching operation on the target class.
    opDef = findCacheOperations(specificMethod.getDeclaringClass());
    if (opDef != null) {
        return opDef;
    }

    if (specificMethod != method) {
        // Fall back is to look at the original method.
        opDef = findCacheOperations(method);
        if (opDef != null) {
            return opDef;
        }
        // Last fall back is the class of the original method.
        return findCacheOperations(method.getDeclaringClass());
    }

    return null;
}

From source file:com.alibaba.dubbo.governance.web.common.module.screen.Restful.java

public void execute(Map<String, Object> context) throws Throwable {
    if (context.get(WebConstants.CURRENT_USER_KEY) != null) {
        User user = (User) context.get(WebConstants.CURRENT_USER_KEY);
        currentUser = user;//from  www. j a  v a 2 s.  c o m
        operator = user.getUsername();
        role = user.getRole();
        context.put(WebConstants.CURRENT_USER_KEY, user);
    }
    operatorAddress = (String) context.get("request.remoteHost");
    context.put("operator", operator);
    context.put("operatorAddress", operatorAddress);

    context.put("currentRegistry", currentRegistry);

    String httpMethod = (String) context.get("request.method");
    String method = (String) context.get("_method");
    String contextPath = (String) context.get("request.contextPath");
    context.put("rootContextPath", new RootContextPath(contextPath));

    // ?Method
    if (method == null || method.length() == 0) {
        String id = (String) context.get("id");
        if (id == null || id.length() == 0) {
            method = "index";
        } else {
            method = "show";
        }
    }
    if ("index".equals(method)) {
        if ("post".equalsIgnoreCase(httpMethod)) {
            method = "create";
        }
    } else if ("show".equals(method)) {
        if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // ????PUTPOST
            method = "update";
        } else if ("delete".equalsIgnoreCase(httpMethod)) { // ????DELETE?
            method = "delete";
        }
    }
    context.put("_method", method);

    try {
        Method m = null;
        try {
            m = getClass().getMethod(method, new Class<?>[] { Map.class });
        } catch (NoSuchMethodException e) {
            for (Method mtd : getClass().getMethods()) {
                if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) {
                    m = mtd;
                    break;
                }
            }
            if (m == null) {
                throw e;
            }
        }
        if (m.getParameterTypes().length > 2) {
            throw new IllegalStateException("Unsupport restful method " + m);
        } else if (m.getParameterTypes().length == 2 && (m.getParameterTypes()[0].equals(Map.class)
                || !m.getParameterTypes()[1].equals(Map.class))) {
            throw new IllegalStateException("Unsupport restful method " + m);
        }
        Object r;
        if (m.getParameterTypes().length == 0) {
            r = m.invoke(this, new Object[0]);
        } else {
            Object value;
            Class<?> t = m.getParameterTypes()[0];
            if (Map.class.equals(t)) {
                value = context;
            } else if (isPrimitive(t)) {
                String id = (String) context.get("id");
                value = convertPrimitive(t, id);
            } else if (t.isArray() && isPrimitive(t.getComponentType())) {
                String id = (String) context.get("id");
                String[] ids = id == null ? new String[0] : id.split("[.+]+");
                value = Array.newInstance(t.getComponentType(), ids.length);
                for (int i = 0; i < ids.length; i++) {
                    Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i]));
                }
            } else {
                value = t.newInstance();
                for (Method mtd : t.getMethods()) {
                    if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set")
                            && mtd.getParameterTypes().length == 1) {
                        String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4);
                        Object v = context.get(p);
                        if (v == null) {
                            if ("operator".equals(p)) {
                                v = operator;
                            } else if ("operatorAddress".equals(p)) {
                                v = (String) context.get("request.remoteHost");
                            }
                        }
                        if (v != null) {
                            try {
                                mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v,
                                        mtd.getParameterTypes()[0]) });
                            } catch (Throwable e) {
                                logger.warn(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
            if (m.getParameterTypes().length == 1) {
                r = m.invoke(this, new Object[] { value });
            } else {
                r = m.invoke(this, new Object[] { value, context });
            }
        }
        if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) {
            context.put("rundata.layout", "redirect");
            context.put("rundata.target", "redirect");
            context.put("success", r == null || ((Boolean) r).booleanValue());
            if (context.get("redirect") == null) {
                context.put("redirect", getDefaultRedirect(context, method));
            }
        } else if (m.getReturnType() == String.class) {
            String redirect = (String) r;
            if (redirect == null) {
                redirect = getDefaultRedirect(context, method);
            }

            if (context.get("chain") != null) {
                context.put("rundata.layout", "home");
                context.put("rundata.target", "home");
            } else {
                context.put("rundata.redirect", redirect);
            }
        } else {
            context.put("rundata.layout", method);
            context.put("rundata.target", context.get("rundata.target") + "/" + method);
        }
    } catch (Throwable e) {
        if (e instanceof InvocationTargetException) {
            throw ((InvocationTargetException) e).getTargetException();
        }
        //            if (e instanceof InvocationTargetException) {
        //                e = ((InvocationTargetException) e).getTargetException();
        //            }
        //            logger.warn(e.getMessage(), e);
        //            context.put("rundata.layout", "redirect");
        //            context.put("rundata.target", "redirect");
        //            context.put("success", false);
        //            context.put("exception", e);
        //            context.put("redirect", getDefaultRedirect(context, method));
    }
}

From source file:org.solmix.runtime.support.spring.AbstractRootBeanDefinitionParser.java

protected void parseAttributes(Element element, ParserContext parserContext, String id,
        RootBeanDefinition beanDefinition) {
    Set<String> props = new HashSet<String>();
    ManagedMap<String, Object> parameters = null;
    for (Method setter : this.type.getMethods()) {
        String name = setter.getName();
        if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers())
                && setter.getParameterTypes().length == 1) {
            Class<?> type = setter.getParameterTypes()[0];
            String property = StringUtils
                    .camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-");
            props.add(property);//from  w ww .  ja  v  a2  s  .c om
            Method getter = null;
            try {
                getter = this.type.getMethod("get" + name.substring(3), new Class<?>[0]);
            } catch (NoSuchMethodException e) {
                try {
                    getter = this.type.getMethod("is" + name.substring(3), new Class<?>[0]);
                } catch (NoSuchMethodException e2) {
                }
            }
            if (getter == null || !Modifier.isPublic(getter.getModifiers())
                    || !type.equals(getter.getReturnType())) {
                continue;
            }
            if ("properties".equals(property)) {
                parameters = parseProperties(element.getChildNodes(), beanDefinition);
            } else if ("arguments".equals(property)) {
                parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
            } else {
                String value = element.getAttribute(property);
                if (value != null && value.trim().length() > 0) {
                    value = value.trim();
                    parserValue(beanDefinition, property, type, value, parserContext);
                }
            }
        }
    }
    NamedNodeMap attributes = element.getAttributes();
    int len = attributes.getLength();
    for (int i = 0; i < len; i++) {
        Node node = attributes.item(i);
        String name = node.getLocalName();
        if (!props.contains(name)) {
            if (parameters == null) {
                parameters = new ManagedMap<String, Object>();
            }
            String value = node.getNodeValue();
            parameters.put(name, new TypedStringValue(value, String.class));
        }
    }
    if (parameters != null) {
        beanDefinition.getPropertyValues().addPropertyValue("properties", parameters);
    }
}

From source file:com.cuubez.visualizer.resource.ResourceMetaDataScanner.java

public SubResource scanMethods(Class<?> clazz, Method method) {

    int modifier = method.getModifiers();

    if (Modifier.isStatic(modifier) || !Modifier.isPublic(modifier)) {
        return null;
    }/* www  . j  a  v  a2 s.  c o  m*/

    SubResource subResource = new SubResource();
    subResource.setReflectionMethod(method);

    if (!scanHttpMethod(subResource, method)) {
        return null;
    }

    scanPath(subResource, method);
    scanConsume(subResource, method);
    scanProduce(subResource, method);
    scanDetail(subResource, method);
    scanName(subResource, method);
    scanHttpCodes(subResource, method);
    scanResponseType(subResource, method);
    subResource.setClazz(clazz);

    return subResource;
}

From source file:com.dianping.resource.io.util.ClassUtils.java

/**
 * Given a method, which may come from an interface, and a target class used
 * in the current reflective invocation, find the corresponding target method
 * if there is one. E.g. the method may be {@code IFoo.bar()} and the
 * target class may be {@code DefaultFoo}. In this case, the method may be
 * {@code DefaultFoo.bar()}. This enables attributes on that method to be found.
 * <p><b>NOTE:</b> In contrast to {@link org.springframework.aop.support.AopUtils#getMostSpecificMethod},
 * this method does <i>not</i> resolve Java 5 bridge methods automatically.
 * Call {@link org.springframework.core.BridgeMethodResolver#findBridgedMethod}
 * if bridge method resolution is desirable (e.g. for obtaining metadata from
 * the original method definition).//from  w  ww . ja v  a2s.  co m
 * <p><b>NOTE:</b> Since Spring 3.1.1, if Java security settings disallow reflective
 * access (e.g. calls to {@code Class#getDeclaredMethods} etc, this implementation
 * will fall back to returning the originally provided method.
 * @param method the method to be invoked, which may come from an interface
 * @param targetClass the target class for the current invocation.
 * May be {@code null} or may not even implement the method.
 * @return the specific target method, or the original method if the
 * {@code targetClass} doesn't implement it or is {@code null}
 */
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
    if (method != null && isOverridable(method, targetClass) && targetClass != null
            && !targetClass.equals(method.getDeclaringClass())) {
        try {
            if (Modifier.isPublic(method.getModifiers())) {
                try {
                    return targetClass.getMethod(method.getName(), method.getParameterTypes());
                } catch (NoSuchMethodException ex) {
                    return method;
                }
            } else {
                Method specificMethod = ReflectionUtils.findMethod(targetClass, method.getName(),
                        method.getParameterTypes());
                return (specificMethod != null ? specificMethod : method);
            }
        } catch (AccessControlException ex) {
            // Security settings are disallowing reflective access; fall back to 'method' below.
        }
    }
    return method;
}

From source file:com.kelveden.rastajax.core.ResourceClassLoader.java

private List<ResourceClassMethod> loadMethods(final Class<?> candidateResourceClass) {

    final List<ResourceClassMethod> methodsOnResource = new ArrayList<ResourceClassMethod>();

    Method[] methods;/*from  w  w w.  j  ava2 s .  co  m*/
    try {
        methods = candidateResourceClass.getDeclaredMethods();
    } catch (NoClassDefFoundError e) {
        LOGGER.warn(
                "Could not process candidate resource class {} as a class referenced in it could not be found.",
                candidateResourceClass.getName(), e);
        return methodsOnResource;
    }

    for (Method method : methods) {
        if (Modifier.isPublic(method.getModifiers())) {
            final ResourceClassMethod methodOnResource = loadMethod(candidateResourceClass, method);

            if (methodOnResource != null) {
                methodsOnResource.add(methodOnResource);
            }
        }
    }

    return methodsOnResource;
}