Wednesday 12 January 2022

Call the main method of one class from other class using reflection

 Step 1: Get an instance of the class.

Class<?> clazz = Class.forName("com.sample.app.Test");

Step 2: Get the main method of Test class.

Method main = clazz.getMethod("main", String[].class);

Step 3: Invoke the main method.

String[] args1 = { "Hello", "Hi!!!!" };
main.invoke(null,  (Object) args1);

Find the below working application.

Test.java

package com.sample.app;

public class Test {
	
	public static void main(String args[]) {
		System.out.println("In the main method of Test class");
		
		if(args == null) {
			return;
		}
		
		for(String arg: args) {
			System.out.println(arg);
		}
	}

}

HelloWorld.java

package com.sample.app;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HelloWorld {

	public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class<?> clazz = Class.forName("com.sample.app.Test");
		Method main = clazz.getMethod("main", String[].class);

		String[] args1 = { "Hello", "Hi!!!!" };

		System.out.println("About to call the main method of Test class");
		main.invoke(null,  (Object) args1);

	}
}

Run main method of HelloWorld class, you will see below output in the console.

About to call the main method of Test class
In the main method of Test class
Hello
Hi!!!!







You may like

Interview Questions

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

instanceof operator behavior with interface and class

No comments:

Post a Comment