简体   繁体   中英

Java - How to use a existing Enum inside class

Can someone give me an example how to use this enum. I'm trying to find out what I need to import and how I can use the methods of the following Enum:

http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/Response.Status.html

Here goes one example in JSON:

public Response retrieveSomething(String uuid) {
    Entity entity = service.getById(uuid);
    if(entity == null) {
        return Response.status(Response.Status.NOT_FOUND).entity("Entity not found for UUID: " + uuid).build();
    }
    String json = //convert entity to json
    return Response.ok(json, MediaType.APPLICATION_JSON).build();
}

You would need the correct package containing the enum definition. In this instance javax.ws.rs . Visit this post to know where to find it.

Can't find javax.ws.rs package in jdk

After you have added the .jar to your CLASSPATH you can simple import it

import javax.ws.rs.core.Response.Status;

In many respects an enum is just like z regular class; the answer is practically the for how to use an enum as how to use a class:

Step 1: import the enum to your program:

import javax.ws.rs.core.Response.Status;

Step 2: Het a reference to an instance (unlike regular classes, you can't create an instance - that is done for you by the JVM), either from the enum:

Status status = Status.OK;

or as the returned value of a method:

Status status = response.getStatus();

Step 3: Invoke a method:

int code = status.getStatusCode();

Here is a very simple example using the Status enum: First import Response:

import javax.ws.rs.core.Response;

Then your code...

public Response create() {
    return Response.status(Response.Status.CONFLICT).build();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM