Reputation: 18068
I would like to display on the console only methods of the class which were not inherited. If I wanted to display all of them I would just use:object.getClass().getMethods();
but then I would get all of the method declared in the class and I would like to get only those which are genuinly declared in the class I am analyzing.
Upvotes: 0
Views: 81
Reputation: 280136
The Method
class has a getDeclaringClass()
method which returns the class in which the method is declared. You can use it like so
public class Driver {
public static void main(String[] args) {
Method[] methods = Driver.class.getMethods();
for (Method method : methods) {
if (method.getDeclaringClass().equals(Driver.class)) {
System.out.println(method);
}
}
}
public void doSomething() {
}
}
In other words, you check if the method is declared in the actual type you are interested in.
Or use what Marko suggested.
Upvotes: 1
Reputation: 200236
There is a method just for what you need: getDeclaredMethods()
. It returns all declared methods, as opposed to getMethods()
, which returns all public methods, whether inherited or not.
Upvotes: 1