given a method name, find the class in which it is defined. - Android java.lang.reflect

Android examples for java.lang.reflect:Method

Description

given a method name, find the class in which it is defined.

Demo Code

/**//from   www  . ja  v a2 s.  co  m
 * utilities to access and set fields in objects via reflection
 * @author Matthew
 * Copyright (c) 2013 Visible Automation LLC.  All Rights Reserved.
 */
//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    /**
     * given a method name, find the class in which it is defined.  This is used to find the first ancestor which
     * defines this method.  For example, we want to find out if someone overrode the android onClick() method to 
     * determine if we want to attach an OnClickListener to this object
     * @param object object to search up from
     * @param methodName name of the method
     * @param types for the method parameters.
     * @return
     */
    public static Class getClassForMethod(Object object, String methodName,
            Class... methodParameters) {
        Class c = object.getClass();
        while (c != Object.class) {
            try {
                Method method = c.getDeclaredMethod(methodName,
                        methodParameters);
                if (method != null) {
                    return c;
                }
            } catch (NoSuchMethodException nsmex) {
            }
            c = c.getSuperclass();
        }
        return null;
    }
}

Related Tutorials