• Skip to primary navigation
  • Skip to content

GitopsCentral

  • Home
  • Courses
  • Roadmap
  • About
  • Log In
  • Sign Up

How to call main method from another main method in Java

May 31, 2019 by shaik zillani

In this blog post, I will show you how to call a main from inside a main method in java using reflection

Let’s start from creating a simple class Hello.java as shown below,

public class Hello {
    public static void main(String[]args){
        System.out.println("Hello");
    }
}

Now, Let’s create another class Test.java which also has a main method and let’s call the main from Hello here,

import java.lang.reflect.Method;

public class Test {
    public static void main(String []args) {
        try {
            Class<?> cls = Class.forName("Hello");
            //System.setProperty(FILENAME, FILEPATH);
            Method meth = cls.getMethod("main", String[].class);
            meth.invoke(null,(Object)args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Optionally you can useSystem.setProperty to pass vm options

Output:

Hello

java java

© Copyright 2016-2025 gitopscentral · All Rights Reserved ·