Can't choose class as main class in IntelliJ
JavaIntellij IdeaJava Problem Overview
I have a Java project in IntelliJ to which I just added a bunch of files in a nested folder hierarchy. Many of these files are tests and include the main method, so I should be able to run them. However I cannot figure out how to do this.
I'm new to IntelliJ and previously files have shown up in the project hierarchy with the symbol that corresponds to "Java class that contains declaration of the main() method." but in this scenario they show up with the symbol corresponding to "Java class located out of the source root."
So how do I compile and run these files?
Java Solutions
Solution 1 - Java
Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"
Solution 2 - Java
The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.
https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html
Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.
Solution 3 - Java
Here is the complete procedure for IDEA IntelliJ 2019.3:
-
File > Project Structure
-
Under Project Settings > Modules
-
Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.
-
Apply changes.
Solution 4 - Java
I also faced another issue: the main method has to have arguments
This way is incorrect, Intellij will not let you select main method.
public class yourClass() {
public static void main() {
This way is CORRECT and Intellij will let you select it
public class yourClass() {
public static void main(string[] args) {
Solution 5 - Java
Sometimes under the current automatically configured sources root you need to specify the module classpath:
- Click Run -> Edit Configurations
- Select the project you can't find the main class for
- Under the
Use classpath of module
pulldown see if there is a sub directory that has your main class under it. If so, select it. - try to configure the main class again.
Solution 6 - Java
I'm using Eclipse but it will be something similar like this.
Right click on project and select something similar to 'Maven' >> 'Reload from maven'.
Intelij should be able to understand project structure from Maven pom file and will select main class automatically.