IntelliJ中如何仅运行单个带main方法的Java类
Fix: IntelliJ Compiles Entire Project When Running a Single Java Class
Hey there, I get your frustration—when you just want to test a quick Hello.java without dealing with broken classes elsewhere in your project, having IntelliJ compile everything is a total pain. Here's how to fix it:
Option 1: Create a Run Configuration for Just the Single File
- Right-click your
Hello.javafile and select Modify Run Configuration (older versions might show Edit Run Configuration instead). - In the configuration window that pops up, look for the Scope setting (usually on the right-hand panel).
- Click the dropdown next to Scope and choose Single file.
- Hit Apply then OK to save the changes.
- Now when you run this configuration, IntelliJ will only compile and execute
Hello.java—no more waiting for the whole project to build, and no errors from other broken classes getting in the way.
Option 2: Tweak the Existing Configuration Temporarily
If you don't want to make a new config, you can adjust your existing Hello.main() setup on the fly:
- Click the run configuration dropdown in the top toolbar (the one showing which class/config you're about to run).
- Select Edit Configurations....
- Find your
Hello.main()entry, change the Scope to Single file. - Run it, and if you need to go back to compiling the whole project later, just switch the Scope back to Project or Module.
Quick Checks If It Still Doesn't Work
- Make sure
Hello.javadoesn't reference any other classes in your project. If it does, IntelliJ will still need to compile those dependencies—that's expected behavior. - Try invalidating caches: Go to File > Invalidate Caches..., check the relevant boxes, and restart IntelliJ. Sometimes cached build data causes weird, unexpected behavior.
- Verify that the directory containing
Hello.javais marked as a Sources Root: Right-click the directory, go to Mark Directory as > Sources Root. IntelliJ needs this to recognize it as valid compileable code.
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

