find Method without throwing exception - Android java.lang.reflect

Android examples for java.lang.reflect:Method

Description

find Method without throwing exception

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    public static Method findMethodNoThrow(Class<?> cls, String name,
            Class<?>... parameterTypes) {
        Method m = null;//  www  . j av  a  2  s. c  o  m
        try {
            m = findMethod(cls, name, parameterTypes);
            m.setAccessible(true);
        } catch (NoSuchMethodException e) {
        }
        return m;
    }

    public static Method findMethod(Class<?> cls, String name,
            Class<?>... parameterTypes) throws NoSuchMethodException {
        try {
            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