IntelliJ如何无需编译直接运行.java文件?
Hey there! I totally get where you're coming from—switching from Python/Perl where you can just fire up a source file with a single command to Java's traditional compile-then-run workflow feels like an extra hoop to jump through at first. Let's break down what's actually happening when IntelliJ runs your .java file, and why it seems like it's skipping the compile step.
First, let's recap the Java basics you already know:
- Java is a compiled language, which means your human-readable
.javasource file needs to be converted into bytecode (a.classfile) by thejavaccompiler before the JVM (Java Virtual Machine) can execute it. - Unlike Python/Perl interpreters that read and execute source code line-by-line, the JVM only understands bytecode.
So why does IntelliJ make it look like you're running the .java file directly? It's just hiding the busywork from you! Here's what's going on behind the scenes when you hit that "Run" button:
- IntelliJ automatically compiles your
.javafile to a.classfile in a temporary directory (you can usually find these in theoutortargetfolder of your project). - It then launches the JVM with that compiled
.classfile—but it adds a special tool to the mix: theidea_rt.jaragent you see in the command line.
Let's look at that command you posted again:
"C:\Program Files\Java\jdk1.8.0_121\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.3.4\lib\idea_rt.jar=63733:C:\Program Files\JetBrains\IntelliJ IDEA Community Ed..."
That -javaagent flag tells the JVM to load IntelliJ's runtime agent. This agent does a few key things:
- It handles communication between the JVM and IntelliJ (so you get console output in the IDE, can set breakpoints for debugging, etc.).
- It ensures the compilation step happens before execution, and points the JVM to the right
.classfile even if you don't see it.
If you want to replicate this manually (to see the magic), you could do:
- Compile your file with
javac MyClass.java(this createsMyClass.class). - Run it with
java MyClass.
IntelliJ just wraps these two steps into one action, plus adds its own tools to make development smoother.
One quick tip: If you're using Java 11 or later, you can run .java files directly from the command line without first compiling with javac! Just use:
java MyClass.java
The JVM will handle compiling it to bytecode in memory and executing it immediately—this might feel more familiar from your Python/Perl days.
内容的提问来源于stack exchange,提问作者Stephen

