• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer

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

Primary Sidebar

en English
ar Arabiczh-CN Chinese (Simplified)nl Dutchen Englishfr Frenchde Germanhi Hindiid Indonesianit Italianja Japanesems Malaypt Portugueseru Russianes Spanishte Telugu

Course Tags

concurrency free go golang

Recent Posts

  • Roadmap to Mastery
  • Increase SSH connection timeout
  • Check Certificate expiry in Kubernetes
  • space invaders in golang
  • creating kubernetes cluster using eksctl
  • Facebook
  • GitHub
  • YouTube

Contact

Navigation

  • goacademy pro

Footer

  • Facebook
  • GitHub
  • Instagram
  • LinkedIn
  • Twitter

info@gitopscentral.com


+91 8341443220

© Copyright 2016-2024 gitopscentral · All Rights Reserved ·