Reputation: 532
Is there any way to avoid methods inherited from Object class. I have the following code :
public void testGetMethods() {
SomeClass sc = new SomeClass();
Class c = sc.getClass();
Method [] methods = c.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
}
All is okay but it also returns me methods from the Object class like hashCode, getClass, notify, equals, etc. The class SomeClass should just have two of its own methods which are m1 and m2.
I want only these methods (m1, m2) printed. Is there any way I can achieve this?
Upvotes: 2
Views: 1468
Reputation: 5755
You can exclude methods from Object (or another class) as follows:
Method[] methods2 = new Object().getClass().getMethods();
HashMap<Method, Boolean> hash = new HashMap<Method, Boolean>();
for (Method method : methods2) hash.add(method, false);
for (Method method : methods) {
if (!hash.containsKey(method)) System.out.println(method.getName());
}
This will allow you to use inherited methods, unlike @rgettman's answer. HashMap is used so the check for which class the method is in occurs in constant time and the runtime is linear.
Upvotes: 1
Reputation: 178363
Use the Class
class's getDeclaredMethods()
method.
Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.
Method[] declaredMethods = c.getDeclaredMethods();
Upvotes: 10