Problem in the GetDeclaredMethods (java)

后端 未结 6 1510
旧巷少年郎
旧巷少年郎 2020-12-10 16:04

I have a small problem in my code

I have 2 classes

public class A {

     public A foo(int a) {return new A();}
}

public class B extends A{

     pu         


        
6条回答
  •  一生所求
    2020-12-10 16:33

    By default, getDeclaredMethods() returns all of the methods for the given class, as well as it's parent classes and interfaces. However, the Method object allows you to test which class a Method belongs to by calling getDeclaringClass() on that Method. So when you cycle through all the Method objects, you can add logic to only print a method if it belongs to the B class.

    Method[] m = b.getClass().getDeclaredMethods();
    for (int i = 0; i < m.length; i++) {
      if (m[i].getDeclaringClass().equals(B.class)) {
        System.out.print(m[i].getName());
      }
    }
    

    EDIT: The above code doesn't work as desired -- it returns B as the declaring class of all methods. The isSynthetic() method appears to work as desired, returning true for an overridden method (one that came from A), but false for one that came from B. So the following code might be what you're looking for.

    Method[] m = b.getClass().getDeclaredMethods();
    for (int i = 0; i < m.length; i++) {
      if (!m[i].isSynthetic()) {
        System.out.print(m[i]);
      }
    }
    

提交回复
热议问题