Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethods.

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:org.apache.struts2.convention.DefaultClassFinder.java

public List<Method> findAnnotatedMethods(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();/*  w  w  w.  ja  v  a 2s  . c om*/
    List<ClassInfo> seen = new ArrayList<>();
    List<Method> methods = new ArrayList<>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof MethodInfo && !"<init>".equals(info.getName())) {
            MethodInfo methodInfo = (MethodInfo) info;
            ClassInfo classInfo = methodInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Method method : clazz.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(annotation)) {
                        methods.add(method);
                    }
                }
            } catch (Throwable e) {
                LOG.error("Error loading class [{}]", classInfo.getName(), e);
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return methods;
}

From source file:com.github.juanmf.java2plant.render.PlantRenderer.java

private void renderClassMembers(StringBuilder sb, Class<?> aClass) {
    List<String> fields = new ArrayList<>();
    List<String> methods = new ArrayList<>();
    List<String> constructors = new ArrayList<>();

    addMembers(aClass.getDeclaredFields(), fields);
    addMembers(aClass.getDeclaredConstructors(), constructors);
    addMembers(aClass.getDeclaredMethods(), methods);

    Collections.sort(fields);//from   ww  w . j  a  v a2 s  .c  o m
    Collections.sort(methods);
    Collections.sort(constructors);

    for (String field : fields) {
        sb.append(field + "\n");
    }
    sb.append("--\n");
    for (String constructor : constructors) {
        sb.append(constructor + "\n");
    }
    for (String method : methods) {
        sb.append(method + "\n");
    }
}

From source file:net.jforum.core.support.hibernate.CacheEvictionRulesTestCase.java

private void executeTargetMethod(Class<?> entityClass, String methodName, Object... args) throws Exception {
    Object entity = this.getBean(entityClass.getName());

    Set<Method> methods = new HashSet<Method>(Arrays.asList(entityClass.getMethods()));
    methods.addAll(Arrays.asList(entityClass.getDeclaredMethods()));

    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            if (args != null && args.length > 0) {
                method.invoke(entity, args);
            } else {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (parameterTypes.length == 1 && parameterTypes[0] == int.class) {
                    //method.setAccessible(true);
                    method.invoke(entity, 0);
                } else {
                    args = new Object[parameterTypes.length];
                    //method.setAccessible(true);
                    method.invoke(entity, args);
                }/*from w ww . ja v a 2 s  . co m*/
            }
        }
    }
}

From source file:com.alibaba.dubboadmin.web.mvc.RouterController.java

@RequestMapping("/governance/applications/{app}/{elements}/{element}/{type}/{action}")
public String appAction(@RequestParam Map<String, String> params, @PathVariable("app") String app,
        @PathVariable("elements") String elements, @PathVariable("element") String element,
        @PathVariable("type") String type, @PathVariable("action") String action, HttpServletRequest request,
        HttpServletResponse response, Model model) {
    if (app != null) {
        model.addAttribute("app", app);
    }//from ww w  .j  a  va2s.  c  o m
    if (elements.equals("services")) {
        model.addAttribute("service", element);
    } else if (elements.equals("addresses")) {
        model.addAttribute("address", element);
    }

    String name = WebConstants.mapper.get(type);
    if (name != null) {
        Object controller = SpringUtil.getBean(name);
        if (controller != null) {
            if (request.getMethod().equals("POST")) {
                Method[] methods = controller.getClass().getDeclaredMethods();
                for (Method method : methods) {
                    if (method.getName().equals(action)) {
                        Class<?> param = method.getParameterTypes()[0];
                        try {
                            if (!param.isAssignableFrom(HttpServletRequest.class)) {
                                Object value = param.newInstance();
                                Method[] mms = param.getDeclaredMethods();
                                for (Method m : mms) {
                                    if (m.getName().toLowerCase().startsWith("set")) {
                                        String methodName = m.getName();
                                        String key = methodName.substring(3).toLowerCase();
                                        String tmp = params.get(key);
                                        Object obj = tmp;
                                        if (tmp != null) {
                                            Class<?> t = m.getParameterTypes()[0];
                                            if (isPrimitive(t)) {
                                                obj = convertPrimitive(t, tmp);
                                            }
                                            m.invoke(value, obj);
                                        }

                                    }
                                }
                                return (String) method.invoke(controller, value, request, response, model);
                            } else {
                                return (String) method.invoke(controller, request, response, model);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            } else {
                try {
                    if (StringUtils.isNumeric(action)) {
                        // action is id, call show method
                        Method show = controller.getClass().getDeclaredMethod("show", Long.class,
                                HttpServletRequest.class, HttpServletResponse.class, Model.class);
                        Object result = show.invoke(controller, Long.valueOf(action), request, response, model);
                        return (String) result;
                    } else {
                        Method m = controller.getClass().getDeclaredMethod(action, HttpServletRequest.class,
                                HttpServletResponse.class, Model.class);
                        Object result = m.invoke(controller, request, response, model);
                        return (String) result;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return "";
}

From source file:com.haulmont.restapi.service.EntitiesControllerManager.java

private Object getIdFromString(String entityId, MetaClass metaClass) {
    try {// ww w  .ja va  2  s  .  com
        if (BaseDbGeneratedIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
            if (BaseIdentityIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                return IdProxy.of(Long.valueOf(entityId));
            } else if (BaseIntIdentityIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                return IdProxy.of(Integer.valueOf(entityId));
            } else {
                Class<?> clazz = metaClass.getJavaClass();
                while (clazz != null) {
                    Method[] methods = clazz.getDeclaredMethods();
                    for (Method method : methods) {
                        if (method.getName().equals("getDbGeneratedId")) {
                            Class<?> idClass = method.getReturnType();
                            if (Long.class.isAssignableFrom(idClass)) {
                                return Long.valueOf(entityId);
                            } else if (Integer.class.isAssignableFrom(idClass)) {
                                return Integer.valueOf(entityId);
                            } else if (Short.class.isAssignableFrom(idClass)) {
                                return Long.valueOf(entityId);
                            } else if (UUID.class.isAssignableFrom(idClass)) {
                                return UUID.fromString(entityId);
                            }
                        }
                    }
                    clazz = clazz.getSuperclass();
                }
            }
            throw new UnsupportedOperationException("Unsupported ID type in entity " + metaClass.getName());
        } else {
            //noinspection unchecked
            Method getIdMethod = metaClass.getJavaClass().getMethod("getId");
            Class<?> idClass = getIdMethod.getReturnType();
            if (UUID.class.isAssignableFrom(idClass)) {
                return UUID.fromString(entityId);
            } else if (Integer.class.isAssignableFrom(idClass)) {
                return Integer.valueOf(entityId);
            } else if (Long.class.isAssignableFrom(idClass)) {
                return Long.valueOf(entityId);
            } else {
                return entityId;
            }
        }
    } catch (Exception e) {
        throw new RestAPIException("Invalid entity ID",
                String.format("Cannot convert %s into valid entity ID", entityId), HttpStatus.BAD_REQUEST, e);
    }
}

From source file:com.sun.faces.config.ConfigFileTestCase.java

public void testNonManagedBeans() throws Exception {
    parseConfig("WEB-INF/faces-config.xml", config.getServletContext());

    ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder
            .getFactory(FactoryFinder.APPLICATION_FACTORY);
    ApplicationImpl application = (ApplicationImpl) aFactory.getApplication();

    ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext());
    Object bean = associate.createAndMaybeStoreManagedBeans(getFacesContext(), "SimpleBean");

    // Assert the methods exist on the created bean..
    try {/*w  w w  .  j  av  a2 s.  c  o m*/
        Class c = bean.getClass();
        Method m[] = c.getDeclaredMethods();
        int methodCnt = 0;
        for (int i = 0; i < m.length; i++) {
            if (m[i].getName().equals("setNonManagedBean")) {
                methodCnt++;
            }
            if (m[i].getName().equals("getNonManagedBean")) {
                methodCnt++;
            }
        }
        assertEquals("non managed bean methods not found", methodCnt, 2);
    } catch (Throwable t) {
        assertTrue(false);
    }

}

From source file:com.linkedin.pinot.common.restlet.PinotRestletApplication.java

protected void attachRoutesForClass(Router router, Class<? extends ServerResource> clazz) {
    TreeSet<String> pathsOrderedByLength = new TreeSet<String>(
            ComparatorUtils.chainedComparator(new Comparator<String>() {

                @Override/*from   w  ww  .j a v a  2 s .c om*/
                public int compare(String left, String right) {
                    int leftLength = left.length();
                    int rightLength = right.length();
                    return leftLength < rightLength ? -1 : (leftLength == rightLength ? 0 : 1);
                }
            }, ComparatorUtils.NATURAL_COMPARATOR));

    for (Method method : clazz.getDeclaredMethods()) {
        Annotation annotationInstance = method.getAnnotation(Paths.class);
        if (annotationInstance != null) {
            pathsOrderedByLength.addAll(Arrays.asList(((Paths) annotationInstance).value()));
        }
    }

    for (String routePath : pathsOrderedByLength) {
        LOGGER.info("Attaching route {} -> {}", routePath, clazz.getSimpleName());
        attachRoute(router, routePath, clazz);
    }
}

From source file:com.sun.faces.config.ConfigFileTestCase.java

public void testConfigManagedBeanFactory() throws Exception {

    parseConfig("WEB-INF/faces-config.xml", config.getServletContext());

    ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder
            .getFactory(FactoryFinder.APPLICATION_FACTORY);
    ApplicationImpl application = (ApplicationImpl) aFactory.getApplication();

    ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext());
    Object bean = associate.createAndMaybeStoreManagedBeans(getFacesContext(), "SimpleBean");

    // Assert the correct methods have been created in the bean
    // Also assert the value returned from the "get" method matches
    // the one specified in the config file.
    ////from   w w  w.j  av  a  2 s  .c o m
    try {
        Class c = bean.getClass();
        Method m[] = c.getDeclaredMethods();
        for (int i = 0; i < m.length; i++) {
            Util.doAssert(m[i].getName().equals("setSimpleProperty")
                    || m[i].getName().equals("getSimpleProperty") || m[i].getName().equals("setIntProperty")
                    || m[i].getName().equals("getIntProperty") || m[i].getName().equals("getTrueValue")
                    || m[i].getName().equals("getFalseValue") || m[i].getName().equals("setNonManagedBean")
                    || m[i].getName().equals("getNonManagedBean"));
            if (m[i].getName().equals("getSimpleProperty")) {
                Object args[] = null;
                Object value = m[i].invoke(bean, args);
                Util.doAssert(((String) value).equals("Bobby Orr"));
            }
        }
    } catch (Throwable t) {
        assertTrue(false);
    }
}

From source file:com.taobao.itest.listener.TransactionalListener.java

/**
 * Gets all methods in the supplied {@link Class class} and its superclasses
 * which are annotated with the supplied <code>annotationType</code> but
 * which are not <em>shadowed</em> by methods overridden in subclasses.
 * <p>/*from   w w  w  .j  a  v a 2  s .c o m*/
 * Note: This code has been borrowed from
 * {@link org.junit.internal.runners.TestClass#getAnnotatedMethods(Class)}
 * and adapted.
 * 
 * @param clazz
 *            the class for which to retrieve the annotated methods
 * @param annotationType
 *            the annotation type for which to search
 * @return all annotated methods in the supplied class and its superclasses
 */
private List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationType) {
    List<Method> results = new ArrayList<Method>();
    for (Class<?> eachClass : getSuperClasses(clazz)) {
        Method[] methods = eachClass.getDeclaredMethods();
        for (Method eachMethod : methods) {
            Annotation annotation = eachMethod.getAnnotation(annotationType);
            if (annotation != null && !isShadowed(eachMethod, results)) {
                results.add(eachMethod);
            }
        }
    }
    return results;
}