Search code examples
javaenumsjar

Compilation error when try to access inner static enum in a .jar file


I'm trying to access a inner static enum Status in a .jar file but I'm getting a compilation error and I don't know why.

Message.java:

package com.sockets.protocol;

public class Message {

    public static enum Status {
        OK, ERROR, PARAMERROR, REQUEST;
    }

    private String operation;

    public Message(String operation) {
        this.operation = operation;
    }

    // more code here but irrelevant for this problem
}

Compiling and creating .jar file:

javac -d . com/sockets/protocol/Message.java
jar -cvf Message.jar com/sockets/procotol/Message.class

Server.java

package com.sockets.server;

import com.sockets.protocol.Message;

public class Server implements Serializable {

    private int port;
    private Message message;

    public Server(int port) {
        this.port = port;
        this.message = new Message("op-test")
        System.out.println("test status: " + Message.Status.OK);
        System.out.println("test operation: " + message.getOperation());
    }
}

When I comment out the first System.out.println the program runs fine. So how can I fix this?

Error message:

[xxx@xxxxxxx src]$ javac -cp .:../library/Message.jar -d . com/sockets/server/Main.java
./com/sockets/server/Server.java:31: error: cannot access Status
        System.out.println("teste message: " + Message.Status.OK);
                                                      ^
  class file for com.sockets.protocol.Message$Status not found
1 error

Solution

  • You need to explicitly put all classes in the jar.

    jar -cvf Message.jar Message.class Message\$Status.class
    

    You'll note that the 'v' option tells you what is going into the jar, and in your case, the Status enum was not listed.

    The name of the enum is Message$Status, but the dollar sign needs to be escaped as \$ if this is Linux or similar.