杰瑞科技汇

Linux下Java class文件如何运行?

Of course! This is a very common task for Java developers. Let's break down everything you need to know about working with .class files on Linux.

Linux下Java class文件如何运行?-图1
(图片来源网络,侵删)

What is a .class file?

A .class file is a platform-independent binary file generated by the Java compiler (javac). It contains Java bytecode, which is a set of instructions that the Java Virtual Machine (JVM) can execute. This "write once, run anywhere" philosophy is the core strength of Java.


Compiling .java to .class (The Basics)

First, you need a Java source file (.java). Let's create a simple one.

Step 1: Create a Java file Open a terminal and create a file named HelloWorld.java:

nano HelloWorld.java

Paste this code into the file and save it (Ctrl+X, then Y, then Enter):

Linux下Java class文件如何运行?-图2
(图片来源网络,侵删)
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, from a compiled .class file!");
    }
}

Step 2: Compile the file Use the Java compiler (javac) to turn HelloWorld.java into HelloWorld.class.

javac HelloWorld.java

If the command succeeds, you won't see any messages, but you'll now have a new file in your directory:

ls -l

You will see: -rw-r--r-- 1 user user 428 Oct 26 10:30 HelloWorld.class -rw-r--r-- 1 user user 92 Oct 26 10:29 HelloWorld.java

You now have your .class file!

Linux下Java class文件如何运行?-图3
(图片来源网络,侵删)

Running the .class File

To run the compiled bytecode, you use the java command. A very common mistake for beginners is to add .class to the end of the command.

Correct way: The java command starts the JVM, which loads the class and runs its main method. You specify the class name, not the file name.

java HelloWorld

Incorrect way (this will cause an error):

# This will NOT work!
java HelloWorld.class

Output of the correct command:

Hello, from a compiled .class file!

Common Scenarios and Commands

A) Multiple Classes in one File

You can have multiple classes in a single .java file, but only one can be public. The public class name must match the filename.

Example: Create Shapes.java:

// File: Shapes.java
public class Shapes {
    public void draw() {
        System.out.println("Drawing a shape.");
    }
}
class Triangle {
    // This class is not public
    public void draw() {
        System.out.println("Drawing a triangle.");
    }
}

Compile it:

javac Shapes.java

This will produce two .class files: Shapes.class and Triangle.class.

You can run both:

java Shapes
# Output: Drawing a shape.
java Triangle
# Output: Drawing a triangle.

B) Classes in Different Files (Packages)

For larger projects, you'll have classes in separate files, often organized into packages.

Directory Structure:

my_project/
├── com/
│   └── example/
│       └── Main.java
└── com/
    └── example/
        └── utils/
            └── Calculator.java

Calculator.java:

package com.example.utils;
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

Main.java:

package com.example;
// Import the other class from its package
import com.example.utils.Calculator;
public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        int sum = calc.add(5, 7);
        System.out.println("The sum is: " + sum);
    }
}

How to Compile and Run:

  1. Compile from the root directory (my_project/): You need to tell javac where to find the source files using the -d flag, which specifies the destination for the generated .class files (usually mirroring the package structure).

    # From inside the my_project directory
    javac -d . com/example/Main.java com/example/utils/Calculator.java

    This command creates a directory structure that matches the packages, containing the .class files.

  2. Run from the root directory (my_project/): To run, you must be in the root directory and specify the fully qualified class name (including the package).

    # From inside the my_project directory
    java com.example.Main

    Output:

    The sum is: 12

Advanced: Using the javap Disassembler

The javap command (Java Disassembler) lets you inspect the contents of a .class file. It's incredibly useful for debugging or understanding how the compiler works.

Basic Usage: Let's inspect our HelloWorld.class file.

javap HelloWorld

Output:

Compiled from "HelloWorld.java"
public class HelloWorld {
  public HelloWorld();
  public static void main(java.lang.String[]);
}

This shows you the class name, its constructor (HelloWorld()), and its methods.

More Detailed Output: Use the -c flag to see the actual bytecode instructions.

javap -c HelloWorld

Output (abbreviated):

Compiled from "HelloWorld.java"
public class HelloWorld {
  public HelloWorld();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return
  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #3                  // String Hello, from a compiled .class file!
       5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return
}

This shows the low-level instructions the JVM will execute.


Managing .class Files in a Project

For any non-trivial project, you should not manually manage .class files. Use a build tool like Maven or Gradle.

  • Maven: Uses a standard directory structure (src/main/java for source, target/classes for compiled .class files). You run mvn compile to build and mvn exec:java -Dexec.mainClass="com.example.Main" to run.
  • Gradle: Also uses a standard structure (src/main/java). You run gradle build to build and gradle run to execute the main class.

These tools automate compilation, dependency management, and packaging (e.g., into a .jar file).


Summary of Key Commands

Goal Command Description
Compile javac MyFile.java Compiles one or more .java source files into .class files in the current directory.
Run java MyClass Executes the main method in MyClass.class. Do not include the .class extension.
Inspect Class (Disassemble) javap MyClass Prints a basic outline of a class.
Inspect Class (Bytecode) javap -c MyClass Prints the bytecode instructions for the class.
Compile with Package Structure javac -d . com/example/MyClass.java Compiles a source file and creates the necessary directory structure for its package in the current dir.
Run with Package Structure java com.example.MyClass Executes a class that is part of a package.
分享:
扫描分享到社交APP
上一篇
下一篇