find Method by name and parameter type - Android java.lang.reflect

Android examples for java.lang.reflect:Method

Description

find Method by name and parameter type

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    public static Method findMethod(Class<?> cls, String name,
            Class<?>... parameterTypes) throws NoSuchMethodException {
        try {//from  ww  w .  ja v a 2 s .  com
            Method m = cls.getMethod(name, parameterTypes);
            if (m != null) {
                return m;
            }
        } catch (Exception e) {
            // ignore this error & pass down
        }

        Class<?> clsType = cls;
        while (clsType != null) {
            try {
                Method m = clsType.getDeclaredMethod(name, parameterTypes);
                m.setAccessible(true);
                return m;
            } catch (NoSuchMethodException e) {
            }
            clsType = clsType.getSuperclass();
        }
        throw new NoSuchMethodException();
    }
}

Related Tutorials