Scalahansolo
Scalahansolo

Reputation: 3015

getMethod avoiding parent classes

While using getMethod(), I've run into a problem. The class I am calling getMethod() on has many parent methods. However, I dont want getMethod to notice the methods of the parent class, only the specific class I am looking at. For example...

class superClass {
    boolean equals(Object obj) {
        ....
    }
}

...

import superClass

class subClass {
    ...
}

Now if I am using getMethod like this...

try{
   Class[] args = new Class[1];
   args[0] = Object.class;
   Method equalsMethod = subClass.getMethod("equals", args);
}

catch(NoSuchMethodException ex){
...
}

I don't want this to pull in the equals method from the superClass, which it currently is doing. All I want to know is if the class I am calling getMethod on (in this case subClass) contains the method equals().

Any way of doing this? Any help would be appreciated.

Upvotes: 2

Views: 1406

Answers (2)

AlexR
AlexR

Reputation: 115328

Use subClass.getDeclaredMethod() instead. This way you will get the method that definitely declared in your class or MethodNotFoundException

Upvotes: 0

Spencer Ewall
Spencer Ewall

Reputation: 189

Give getDeclaredMethod(String, args) a try. It will only return methods explicitly declared by your class, so no supers involved.

Upvotes: 4

Related Questions