Multiple main methods in java package - java

I have a project in NetBeans where two different classes have public static void main(String[] args) methods.
When I press F6, the first class' main is always invoked. Why not the second? When I'm trying to display arguments of args, it says that this array is empty.

In the project properties, in the Categories, choose Run.
then there is a Main Class.
Set your main class there

I don't know Netbeans, but in Eclipse it automatically sets up a launch config which you can easily customise to specify the full package and class name containing the main class.
Ultimately any program launch is going to effective be a command line execution so I'd expect that netBeans must have a way to customise it as well. You just need to find that and adjust the launch (or setup a new one) for your second program.

Related

JavaFX runtime main method

The Hello World-Tutorial of JavaFX says:
The main() method is not required for JavaFX applications when the JAR file for the application is created with the JavaFX Packager tool, which embeds the JavaFX Launcher in the JAR file. However, it is useful to include the main() method so you can run JAR files that were created without the JavaFX Launcher, such as when using an IDE in which the JavaFX tools are not fully integrated. Also, Swing applications that embed JavaFX code require the main() method.
I tried this and its true, I can start my application without a main method.
However when I declare a main method an call launch from the Application class, the program still works.
The documentation of Application says, that the JavaFX runtime is creating an instance of the Application class and calls the init method.
But how does the JavaFX runtime start? I mean there has to be a main method somewhere, for everything to start. So Iam wondering if I declare a main method by myself, arent there two of them?
I've actually always been interested in how Java launches JavaFX applications, so I decided to debug the process. Some things before the rest of the answer:
I did the debugging with JDK-10 for a standalone desktop application. Some quick glances at the JDK-11 source code suggests the process has not changed between versions.
When I use Application I'm referring to the javafx.application.Application class.
When I use "main method" I'm referring to the public static void main(String[] args) method. Similarly, "main class" refers to the class containing the main method.
All links for source code point to the OpenJDK Mercurial repository.
Virtually all of this is an implementation detail and is subject to change without notice.
Summary
When launching a JavaFX application, if the main class is a subclass of Application then the Java launcher uses it's own, internal main class. This internal class is responsible for initializing the JavaFX toolkit. Once the toolkit is initialized, one of two things can happen.
The Application subclass has a main method.
In this case, some internal JavaFX code invokes the main method. It is now the developers responsibility to finish launching the application via Application.launch.
The Application subclass does not have a main method.
In this case, the same internal JavaFX code launches the application itself. The first case eventually ends up in the same place this case does.
Basically, any main method declared in Application subclasses are not "normal" main methods. Think of this behavior like this:
The internal main method acts as the entry point for the Java application—just like all "normal" main methods
The Application subclass' main method serves as an optional entry point for the JavaFX application, where the JavaFX toolkit is already initialized.
Detailed Answer
First, it is not the case that you "override" the main method of the Application class; the Application class has no main method. What actually happens is that Java uses it's own main class whenever the application's declared main class is a subclass of Application. For posterity, a main class can be declared using one of the following:
Specifying it on the command line (file): java -cp <classpath> foo.Main
Specifying it on the command line (module): java -p <modulepath> -m foo/foo.Main
Specifying it in the JAR manifest: Main-Class: foo.Main
(Another way I'm forgetting?)
The Steps
These steps assume a JavaFX application. Most of this doesn't happen if launching a "regular" Java application.
Step 1: Load the Main Class
An internal class, LauncherHelper, checks and loads the main class via a method named checkAndLoadMain. This method is responsible for resolving the main class based on how the main class was declared (described above). Once found, this method checks whether or not the main class is a subclass of Application. If it is, then the main class is changed to a static inner class: LauncherHelper$FXHelper. Then some validation is performed and the Class is returned to, I assume, native code.
Relevant code:
java.base/sun.launcher.LauncherHelper
java.base/sun.launcher.LauncherHelper.checkAndLoadMain
java.base/sun.launcher.LauncherHelper$FXHelper
Step 2: Invoke the main Method
After the main class has been found, loaded, and validated it is called from (I assume) native code. Since we are talking about a JavaFX application the main class is now LauncherHelper$FXHelper. The main method of this class does one simple thing: Invoke internal JavaFX code via reflection.
Relevant code:
java.base/sun.launcher.LauncherHelper$FXHelper.main
Step 3: JavaFX Pre-Startup
The code invoked by step 2 is inside a class named LauncherImpl; specifically, the launchApplication(String,String,String[]) method. This method appears to do similar things as LauncherHelper.checkAndLoadMain except more specific to JavaFX.
I believe this method is similar to checkAndLoadMain because the checkAndLoadMain method validated the FXHelper class, which is obviously valid. However, launchApplication needs to validate the Application subclass.
Relevant code:
javafx.graphics/com.sun.javafx.application.LauncherImpl
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication
Step 4: JavaFX Startup
The next method called is launchApplicationWithArgs(ModuleAccess,String,String,String[]). This method is responsible for starting the JavaFX toolkit. After this, it loads the Application subclass and, if present, Preloader subclass as actual Class instances. It does this on the JavaFX Application Thread but then returns to the main thread.
The code then takes one of two paths depending on the presence of a main method in the Application subclass:
A main method exists: Proceed to step 5.
A main method does not exist: Proceed to step 6 (launch the application directly)
Relevant code:
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs
Step 5: Invoke main Method of Application Subclass (Optional)
If there is a main method in the Application subclass it is invoked via reflection. It is now the responsibility of the developer to continue the launching procedure via a call to Application.launch. There are two overloads of the launch method:
Application.launch(String...)
Application.launch(Class,String)
The only difference being the first option uses the calling Class as the JavaFX Application subclass. Both end up calling LauncherImpl.launchApplication(Class,String[]). This latter method simply loads the Class of the Preloader, if needed, and then continues on to the next step.
Relevant code:
javafx.graphics/javafx.application.Application.launch(String...)
javafx.graphics/javafx.application.Application.launch(Class,String...)
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication
Note: Different method than the one linked in step 3.
Step 6: Finish Launching JavaFX Application
Now we're in the LauncherImpl.launchApplication(Class,Class,String[]) method. This method does two simple things:
Create and start the JavaFX-Launcher thread which calls another method
LauncherImpl.launchApplication1(Class,Class,String[])
Park the main thread (or whatever thread called Application.launch) in a CountDownLatch until the JavaFX toolkit exits.
The launchApplication1 method will start the JavaFX toolkit if it hasn't already been started. Then it continues on to implement the standard JavaFX life-cycle. This involves creating the Application and, if present, Preloader classes then calling the init() and start(Stage) methods at the appropriate times on the appropriate threads. This life-cycle is the publicly defined behavior; virtually everything else mentioned here are implementation details.
Relevant code:
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication
Note: Again, different method from the ones linked in steps 3 and 5.
javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1
Non-Application Main Class
There is another way to launch JavaFX applications where the main class is not a subclass of Application, like so:
// main class
public class Main {
public static void main(String[] args) {
Application.launch(App.class, args);
}
}
// JavaFX Application class
public class App extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
// setup and show primaryStage
}
}
Since Main is not a subclass of Application the change to FXHelper, in step 1, doesn't take place. This also means that steps 2-5 don't happen automatically. Instead, the call to Application.launch in Main starts this process at the final step: 6. That's why the the launchApplication1 method also tries to start the JavaFX toolkit since it wouldn't have been started in this scenario.
One possible answer would probably be, that there is a main method declared in Application. And if another class, which extends from Application, has its own main method, the code would still be valid and the main method of Application will be ignored::
class Main extends OtherMain {
public Main(String text) {
System.out.println(text);
}
/* If this method is removed, the main-method is called from OtherMain */
public static void main(String[] args) {
new Main("Called from Main-Class");
}
}
class OtherMain {
public static void main(String[] args) {
new Main("Called from Other-Main-Class");
}
}
Does this make sense?

In java, do I always need a Main class?

I know that I'll need a main method, but can that main method be in a different class other than the Main class?
Not all Java applications require a main method.
Java can also be used to create web applications, for instance, which don't require main methods to run.
The answer to your question depends on what exactly you mean. Do you mean a class with the name 'Main'? Then, no, there is no requirement for this at all.
The only requirement that Java has, is that the signature of the method is correct. the main method must:
be public
be main
be static
have returntype void
accept an array of Strings as (only) parameter
It's easier to add it in the public class in a file, but not mandatory. The name of the class it is in, is entirely up to you, though many will choose a name like 'Main' or 'Open', simply to more easily find it.
If you want to be able to run your application, by simple double-clicking the .jar file, you'll need to point to the class that contains the main method (to use: your application might contain a lot of main classes, used for internal testing, but only one can be used to start the actual application) in the manifest file: Manifest files
Prior to Java 7, it was possible to run a desktop application without a main method, by (ab)using an instantiation block, but this was removed as of Java 7, because this is not what the instantiation block was intended for.
It's not necessary to define yout main method in a main class. You can place your main method wherever you want, as long the syntax i correct :
public static void main (String[] args){
//...
}
You absolutely don't.
The method itself can be placed whereever you want it to be, there is no limitation.
However, I personally would recommend putting it in a class which at least contains something like "Main", because when others look at your code, and they are not using an IDE which supports jumping to the main method, people usually have an easier time finding your starting point.
However, that is just for sake of readability, and as I said, jumping to main is/should be usually a widespread supported feature
Yes, the Main method is required to run a function although a java class can be without the Main method. Though, it won't run...

Eclipse export as runnable JAR

I know SO dislikes this type of questions but after googling and checking SO for close to an hour I am no closer to a solution. I have a package with some classes which together form a GUI based game which runs fine when I do CTRL-F11 but when I right-click the package->Export->Runnable JAR it is nowhere to be found in the Launch Configuration dropdown, while other packages/projects are.
I would like to be able to run this game outside of Eclipse even if I don't need to now. I have no main methods, my runnable uses acm. public class SokobanGFX extends GraphicsProgram.
Found this in Javadoc:
http://jtf.acm.org/javadoc/student/acm/program/Program.html
"In many programming environments, objects that are specific instances of a Program
subclass will run automatically without any special action on your part. For maximum
portability, you might want to define a static main method as described in the comment
for the standard implementation of main."
Should be easy to make an executable jar after that.
I'm not familiar with ACM, but based on my observations with the Javadoc, I believe:
public static void main(String[] args){
new SokobanGFX().start()
}
//http://jtf.acm.org/javadoc/student/acm/program/Program.html#main(String[])
Should launch the program.

Run multiple java main classes at once in netbeans

I have several main classes with different arguments. I also added the arguments to each class successfully.
But the problem is: I have to start each class manually every time (e.g. click on Run-File).
Is there a solution where I can start all the classes with one click in netbeans? And the classes should also follow a specific order.
Open a new project with a specific name (File -> New project and complete the walk-thru) in NetBeans.
You can create any number of new classes under one project by going to File -> New File -> and completing the walk-thru. At this point of time you should not include main method in these classes. Do not open a new project each time.
Create yet another file (by going thru File -> New File etc.). This time in this new class include code for the main method. From the main method you can call any number of classes by creating instances of those classes. The classes will be executed in the order you called them under the main method as long as all those classes are included in the same folder, that is under the same project.
It looks like you are writing java programs just as do it in the procedural languages. To some extent java classes are like subroutines of the procedural languages. Calling them is done by creating an instance of that class.
Maybe call to each class seperately? For instance:
FirstClass.java
SecondClass.java
ThirdClass.java
In FirstClass, you could call on SecondClass to pop-up, simply with a setVisible(true) if that's all you want it to do. Then in the SecondClass call to ThirdClass to pop-up the same way.
I'm not sure if this is what you wanted as there's no code to go off of, but just something to get you thinking.
You can attempt to run multiple main classes via different run configurations.
See http://wiki.netbeans.org/FaqTwoMainClassesWithArguments
Set one class as main class through properties and run and in that you can Use following code:
ClassName variableName = new ClassName();
variableName.setVisible(true);
ex- Suppose my class name is Dog and I use frame as variable name
Dog frame = new Dog();
frame.setVisible(true);*emphasized text*
Drawing from comments and the question, I understand that you want to run ~5 different java programs simultaneously in your IDE (netbeans,) and the startup sequence has to be in a particular order. I assume you don't need CLI input for these programs once they're running.
I'm unaware of a netbeans way to accomplish your goal, although in Eclipse a Launch Group would satisfy your requirements.
IDE's aside, we can programmatically accomplish this goal anyway. The main() method in Java is just a static method, so if all your main methods are in one project, then you can just make a LaunchSequence class or something and do the following:
public static void main(String[] args)
{
Thread t1 = new Thread()
{
#Override
public void run()
{
ServerOneClass.main(whateverArgsItNeeds);
}
};
t1.start();
Thread t2 = new Thread()
{
#Override
public void run()
{
ClientOneClass.main(whateverArgsItNeeds);
}
};
t2.start();
//and so on.
//The order is enforced by the order you call start(), not the order in which you declare the threads
}
If you have the code for these things in different projects, then you could make a new project and add them as dependencies.
If you do actually need user input for all the programs, you may benefit from looking at Running a java program from another java program

C++ .NET equivalent to java public static void main()?

In java I can simply test classes directly with
public static void main()
I then just add quick code and under Eclipse "Run" the class. Is there anything similar in C++ .NET ?
Right now I have to create an empty project, reference the correct headers then set that project as start up project.
Unit tests. There's also the object test bench if you're using VS.
I do this in C# so I don't know if this will react any differently, but I set up an empty "test" class with the main method and then set the project to startup with that class file. You shouldn't have to create the file in a separate project.
I'm not terribly familiar with Eclipse but if you're just looking to run your objects in the IDE do the following.
Open up the Immediate window and just call whatever function you want. This will start execute the code you type. You will likely have to qualify the name. Ex: ClassLibrary1.MyClass.SomeMethod()
I like using TestDriven.NET for this. It allows you to execute any public method by rightclicking on the header and selecting "Run test".
I like making
public static void Test()
methods on dialog- and form-classes to use with this feature.
It supports C++/CLI, so if that is what you mean by C++.NET, it should work for you.
Edit: You should only do that for things that are not automatically testable - such as pure GUI classes. Otherwise I agree with the other commenters: use a unit test framework.

Categories

Resources