Java Reflection. Where is the method inherited?

May I know from which class a given method implementation is inherited? for example in the current object that is used to implement toString () from Object or some other parent class?

+3


source to share


1 answer


Try it Method.getDeclaringClass()

( 1.5 API link )

public Class<?> getDeclaringClass()

Returns a class object that represents the class or interface that declares the method represented by this Method object.

Specified by:   getDeclaringClass in interface Member

Return:    an object representing the base element's declaration class


Note that you cannot know if the implementation class only calls super

:

public String toString() {
    return super.toString();
}

      


To define the class from which a method is inherited, you need:

class.getMethod("myMethod").getDeclaringClass();

      




Example:

public static void main(String[] args) throws Exception {
  System.out.println(String.class.getMethod("toString").getDeclaringClass());
  System.out.println(ArrayList.class.getMethod("toString").getDeclaringClass());
  System.out.println(Area.class.getMethod("toString").getDeclaringClass());
}

      

Outputs:

class java.lang.String
class java.util.AbstractCollection
class java.lang.Object

      


I noticed from the question that you want a superclass that overrides the method, if available. Here's a demo:

import java.lang.reflect.Method;

public class ReflectionCode {
    public static void main(String[] args) throws SecurityException, NoSuchMethodException, ClassNotFoundException {
        System.out.println(getInheritedClass(Parent.class.getName(),"overRiddenMethod"));
        System.out.println(getInheritedClass(Child.class.getName(),"overRiddenMethod"));
    }

    public static String getInheritedClass(String className, String method){
        Class clazz;
        try {
            clazz = Class.forName(className);

            if(clazz.getSuperclass() != null && clazz.getSuperclass().getMethod(method) != null)
            {
                return clazz.getSuperclass().getName();
            }
        }catch(Exception e){

        }
        return "none";
    }
}

class Parent  {

    public void overRiddenMethod(){

    }
}

class Child extends Parent {

    public void overRiddenMethod() {

    }
}

      

+6


source







All Articles