shay
shay

Reputation: 1221

Reflection in java, methods inheritance

is there a way to get only the methods that myObject decleard (not only public) without getting the inherited methods ?

Upvotes: 0

Views: 56

Answers (2)

Dickens A S
Dickens A S

Reputation: 4054

Let us assume you hav 2 classes name is MyClass and MyParentClass

class MyParentClass {
   private void method1(){}
   public void method2(){}
}
class MyClass extends MyParentClass {
   private void method3(){}
   public void method4(){}
}

You can use getDeclaredMethods() as follows which is give only the methods of MyClass

public class TestClass {
   public static void main(String args[]){
     Method[] m = MyClass.class.getDeclaredMethods();
     for(int i = 0; i < m.length; i++) {
        System.out.println("method = " + m[i].toString());
     }
   }
}

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You're looking for Class#getDeclaredMethods:

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Upvotes: 4

Related Questions