Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid methods inherited from Object class in Java when examining a class with reflection?

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?

like image 764
afym Avatar asked Feb 20 '26 14:02

afym


2 Answers

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();
like image 174
rgettman Avatar answered Feb 22 '26 03:02

rgettman


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.

like image 44
La-comadreja Avatar answered Feb 22 '26 03:02

La-comadreja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!