Search code examples
javajvm.class-file

What is the minimal Java class file that works on every JVM?


I want a sort of minimal "smoke test" for a series of JVMs, ranging from JDK 1 - 8, OpenJDK, IBM JDK, and even Microsoft JDKs if possible. Is there a way to make a minimal Java class file that should be able to test this?

Update

It should be possible to run:

java -cp ClassName

And have output that confirms that the JVM is running properly.

Also, for those who think that JVMs are always functioning should know that I use systems which have up to 20 JVMs on one machine, and some of the JVMs can be corrupted. Also note that not all JVMs can run all .class files


Solution

  • Krakatau has an example aseembler file for the minimal classfile.

    .class public minimal
    .super java/lang/Object
    

    This will give you the simplest possible classfile that will load in the JVM. It doesn't have all the optional metadata that you'll usually get from other tools (Jasmin for instance always adds a SourceFile attribute). This isn't the shortest possible file since you can shave off a few bytes by shortening the class name, but it's basically the simplest possible class.

    Note that while this class will load, it doesn't contain any code so you can't meaningfully execute it. If you want something you can run as the entry point, you'll need to add a main function. This can be done by adapting the Hello World example to remove the printing code.

    .class public Code
    .super java/lang/Object
    
    .method public static main : ([Ljava/lang/String;)V
        .limit stack 10
        .limit locals 10
    
        return
    .end method
    

    This will give you a class that is runnable, and which immediately returns. So it's the simplest possible class with a main function.