Tuesday 12 July 2022

getMethods() vs getDeclaredMethods() in Java reflection

Class.getMethods return the public methods of this class and the public methods inherited from super classes (in simple terms, getMethods ignore non-public methods from this class and super classes.).

 

Class.getDeclaredMethods return all the methods declared in this class.

 


Let’s confirm the same with below example.

 

A.java

package com.sample.app.dto;

public class A {

	public void aPublicMethod() {
		System.out.println("Inside aPublicMethod");
	}

	protected void aProtectedMethod() {
		System.out.println("Inside aProtectedMethod");
	}

	void aDefaultMethod() {
		System.out.println("Inside aDefaultMethod");
	}

	private void aPrivateMethod() {
		System.out.println("Inside aPrivateMethod");
	}

}

 

B.java

package com.sample.app.dto;

public class B extends A{
	public void bPublicMethod() {
		System.out.println("Inside bPublicMethod");
	}

	protected void bProtectedMethod() {
		System.out.println("Inside bProtectedMethod");
	}

	void bDefaultMethod() {
		System.out.println("Inside bDefaultMethod");
	}

	private void bPrivateMethod() {
		System.out.println("Inside bPrivateMethod");
	}
}

ReflectionDemo.java

package com.sample.app;

import java.lang.reflect.Method;

import com.sample.app.dto.A;
import com.sample.app.dto.B;

public class ReflectionDemo {

	private static void printMethodNames(Method[] methods, String message) {
		System.out.println(message);
		for (Method method : methods) {
			System.out.println(method.getName());
		}
		System.out.println("\n");
	}

	public static void main(String[] args) {
		Method[] aMethods = A.class.getMethods();
		Method[] aDeclaredMethods = A.class.getDeclaredMethods();

		Method[] bMethods = B.class.getMethods();
		Method[] bDeclaredMethods = B.class.getDeclaredMethods();

		printMethodNames(aMethods, "A.class.getMethods() : ");
		printMethodNames(aDeclaredMethods, "A.class.getDeclaredMethods() : ");
		printMethodNames(bMethods, "B.class.getMethods() : ");
		printMethodNames(bDeclaredMethods, "B.class.getDeclaredMethods() : ");
	}

}

Output

A.class.getMethods() : 
aPublicMethod
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll


A.class.getDeclaredMethods() : 
aPublicMethod
aProtectedMethod
aDefaultMethod
aPrivateMethod


B.class.getMethods() : 
bPublicMethod
aPublicMethod
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll


B.class.getDeclaredMethods() : 
bPublicMethod
bProtectedMethod
bDefaultMethod
bPrivateMethod


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment