find Method from class by name using reflection - Java Reflection

Java examples for Reflection:Method Name

Description

find Method from class by name using reflection

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        String name = "java2s.com";
        System.out.println(findMethod(clazz, name));
    }// w ww .j a v  a2s . c o  m

    public static List<Method> findMethod(Class<?> clazz, String name) {
        List<Method> ret = new ArrayList<Method>();
        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
            Method[] methods = (c.isInterface() ? c.getMethods() : c
                    .getDeclaredMethods());
            for (Method method : methods) {
                if (name.equals(method.getName()))
                    ret.add(method);
            }
        }
        return ret;
    }
}

Related Tutorials