简体   繁体   中英

How can I get the implementing class for a given method?

Given a few classes/interfaces.

public interface A {
    public int doSomthing(int x);
}

public class B implements A {
    int doSomthing(int x){
        //actually do something
    };
}

public class C extends B {
    //does some specific implementations of what B does
    // but does NOT override "int doSomething(int)"
}

How in a code using implementation C (or any subClass of C) may I determine (programatically) that B was the class implementing int doSomething(int).

Or if any of B's subclasses (lets say D which extends C) overrid "int doSomething(int)" how, when working with E (which extends D, yeah ... this is one large family of classes) may I define first parent that implemented "int doSomething(int)" ?

Thank you all in advance :)

You can do that using reflection, ie you start at the class the object has and check whether that class defines the method which is identified by the methodname and parameter types. If the class doesn't define that method you get its super class and check this, until you hit Object in which case the method isn't available at all.

For public methods, it's easier since Java has already a built-in method for this:

Class<?> mostSpecificImplementor = 
  yourObject.getClass().getMethod( "doSomthing", int.class ).getDeclaringClass();

Note that this only works for public methods, otherwise you'd have to search up the class hierarchy yourself (use getDeclaredMethod(...) in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM