Reputation: 605
public class A{
public static void main(String[] args)
{
//Main code
}
}
public class B{
void someMethod()
{
String[] args={};
A.main();
System.out.println("Back to someMethod()");
}
}
Is there any way to do this? I found a method of doing the same using reflection but that doesn't return to the invoking code either. I tried using ProcessBuilder
to execute it in a separate process but I guess I was missing out something.
Upvotes: 29
Views: 62688
Reputation: 175
Actually, you can call main
method like the way you have just asked but not the way you have done it. First, every execution process starts from the main
method. So, if you want to do it the way you want you can do right this way. This code will execute Hello! World
eight times:
class B
{
B()
{
while(A.i<8)
{
String a[]={"Main","Checking"};
A.main(a);
}
System.exit(0);
}
}
class A
{
public static int i=0;
public static void main(String args[])
{
System.out.println("Hello! World");
i++;
B ob=new B();
}
}
` The iteration part, you can leave it if you want. I Hope I gave you the solution just the way you wanted. :)
Upvotes: 3
Reputation: 9775
Yes you can do call A.main()
.
You can do this:
String[] args = {};
A.main(args);
If you don't care about the arguments, then you can do something like:
public static void main(String ... args)
and call it with:
A.main(); //no args here
Upvotes: 6
Reputation: 1788
There's nothing magic about the name "main". What you've sketched ought to work, so your problem must be something else. Test my claim by changing the name of "main" to something else, I bet it still doesn't work.
Upvotes: 3
Reputation: 4531
Of course. String[] args = {}; A.main(args);
Just be aware: from purely what you have up there, the main method is still the entry point to the program. Now, if you are trying to run the main method in a new PROCESS, this is a different story.
Upvotes: 1
Reputation: 1500285
Your code already nearly does it - it's just not passing in the arguments:
String[] args = {};
A.main(args);
The main
method is only "special" in terms of it being treated as an entry point. It's otherwise a perfectly normal method which can be called from other code with no problems. Of course you may run into problems if it's written in a way which expects it only to be called as an entry point (e.g. if it uses System.exit
) but from a language perspective it's fine.
Upvotes: 42