I can't find an answer to this question anywhere so I'm hoping someone can help me out. I'm expecting that what I am asking is not possible, but I wanted to confirm. First, an enum example...
public enum StatusCode {
SUCCESS(0), GENERAL_ERROR(999), CONNECTION_TIMEOUT_ERROR(1337);
private int statusCode;
private StatusCode(int statusCode) {
this.statusCode = statusCode;
}
public int getStatusCode() {
return statusCode;
}
}
As you can see, I am using this enum to force specific status codes. My question is this: Is there a way that I can reference StatusCode.SUCCESS and have it return the int value associated with it? Rather than get into too much detail about what I would like to do, take this example:
public String getStatusMessage(int statusCode) {
// Map<Integer, String> that contains status messages
// return String for key statusCode
}
In this example, the syntax for calling this method is getStatusMessage(StatusCode.SUCCESS.getStatusCode()).
Is there a way to shorten this to getStatusMessage(StatusCode.SUCCESS)?
I think the second way looks much cleaner and would make my code much more readable. Any ideas? Any help is much appreciated. Thanks in advance!
You mean like this?
public String getStatusMessage(StatusCode code) {
int status = code.getStatusCode();
String message = ...do stuff to get message :)
return message;
}
Luckily for you, EnumMap exists just for that situation.
private static final Map<StatusCode, String> mapMessage =
new EnumMap<>(StatusCode.class);
mapMessage.put(SUCCESS, "Success.");
...
You don't even need the method getStatusMessage, just call map.getMessage(SUCCESS).
However maybe you would be better off adding a String message field within StatusMessage and calling the constructors like SUCCESS(0, "Success") and then adding a getter for the message.
Related
Im here again to ask help about a little ( i hope is little) problem.
What my friend told me to do, is to add a view/click counter in the GET request and save it into a DATABASE (actualy working with DBEAVER).
I m still looking for a way to do it but i have no idea. can you help pls ? Here the code.
oh btw im using springtools
this is the controller:
#Controller
#RequestMapping("/")
public class RecipeController {
//ADMIN- USER
#GetMapping("/user")
public String user() {
return "user";
}
#GetMapping("/admin")
public String admin() {
return "admin";
}
and this is the model
private int hitCount;
public int getHitCount() {
return hitCount;
}
public void setHitCount(int hitCount) {
this.hitCount = hitCount;
}
i hope is enough clear, is more info is need im here :D
Thx alot
2 options come to my mind :
Create another service-class, which will have a method to track (and update) the API-call count, (you can make DB calls in that method).
Use annotations(AOP) to make a generic handler for tracking the API call counts. Try searching for #Before it comes from org.aspectj.lang.annotation package.
Say I have a function that looks at a file and returns two results: recognized and unrecognized. When it returns the recognized result, I want the result to also contain a message but when it is unrecognized, no message is necessary.
public Result checkFile(File file) {
...
}
There are two ways I can think of to accomplish this...
Have the Result class like so:
class Result {
private Type type;
private String message;
enum Type {
RECOGNIZED, UNRECOGNIZED
}
}
Or do it like so:
class Result {
}
class Unrecognized extends Result {
}
class Recognized extends Result {
private String message;
}
I'm inclined to use the second method, even though I'd have to check the result using instanceof and I've read that instanceof should be avoided whenever possible, but doing this avoids having a null message when the result is unrecognized. For this example a null message wouldn't be much of an issue, but what if there is a lot more data associated with a recognized result? It seems like worse practice to me to instantiate a class that could have all null fields.
What is the best practice to handle this situation? Is there some standard method or pattern?
Two classes might be overkill, because of it being one and the same class of object. Also an enum with two values which merely reassemble true and false is not required. One class Result should suffice and this would also remove the demand for a common interface. I'd be all for "no complexity beyond necessary" ...
class RecognitionResult {
private String message = "default message";
private boolean recognized = false;
public Result() {}
public Result(boolean value) {
this.setRecognised(value);
}
public boolean setRecognised(boolean value) {
this.recognized = value;
}
public boolean setMessage(#NonNull String value) {
this.message = value;
}
public boolean getRecognised() {
return this.recognized;
}
#Nullable
public String getMessage() {
return this.recognized ? this.message : null;
}
}
then one can simply do:
return new RecognitionResult(true);
an interface for asynchronous callbacks might look alike this:
interface Recognition {
void OnComplete(RecognitionResult result);
}
or if you really want to optimize:
interface Recognition {
void OnSuccess(RecognitionResult result);
void OnFailure(RecognitionException e);
}
Of course there's no 'correct' design here - it's going to be a matter of opinion which way you go. However my view is that the modern trend in OOD is to minimise the use of extension and to use delegation and implementation of interfaces wherever possible.
As a general rule, whenever you think of using instanceof, reconsider your design.
This would be my suggestion:
interface Result {
boolean isRecognised();
String getMessage();
}
class RecognisedResult implements Result {
private final String message;
public boolean isRecognised() {
return true;
}
public String getMessage() {
return message;
}
}
class UnrecognisedResult implements Result {
public boolean isRecognised() {
return false;
}
public String getMessage() {
throw new UnsupportedOperationException("No message for unrecognised results");
}
}
you can look at the way Retrofit implement your concept of "recognised" and "message"
https://square.github.io/retrofit/2.x/retrofit/retrofit2/Response.html. it is similar to your first method.
what they did is to have a class called Response, containing a method called isSuccessful(), and a method called body() containing the payload if it's successful (or null if it is unsuccessful.
you can try some thing like the following
class Result {
private Type type;
private String message;
public bool isSuccessful(){
return type == RECOGNIZED;
}
public String getMessage(){
return message; //null if unrecognized.
}
enum Type {
RECOGNIZED, UNRECOGNIZED
}
}
The functional way to do this would be to use an Either type, which doesn’t come with the JDK, but is available in vavr library. Based on your comments on this thread, it appears you don’t clearly understand how type inheritance works. In that case, a functional solution may be overkill, and I’d suggest going with #sprinter’s solution.
G'day, errata ... My plan was as shown below. This update is to clarify and apologise for a late night question. The compile error was due to a problem elsewhere in the file.
Clarification: a simple Java enum, like this:
public enum ServiceSource
{
NONE,
URL,
FILE;
}
Want to checking like, isURL():
public boolean isURL(){
return (URL == this);
}
This works (and compiles) ... There's no question -- Correctly answered by: dasblinkenlight and Elliott Frisch. Thank you very much for your time.
see also:
Lookup enum by string value
How to test enum types?
Since this is an instance method, you need to check that this is equal to URL, like this:
public boolean isURL(){
return (URL == this);
}
Demo on ideone.
If you want to have methods that are polymorphic - i.e. exhibit different behaviour for different instances (values) of your enum class, my preference is to override a common method:
public enum ServiceSource {
NONE("no_value"),
URL("url"){
#Override
public boolean isURL() {
return true;
}
},
FILE("file");
private final String val;
private ServiceSource(String val) {
this.val = val;
}
public boolean isURL() {
return false;
}
}
But for methods that check whether this is specific enum value then adding an isXXX method for each constant seems very wasteful. Really, the very reason to use an enum, is so that you can write
if(thing == ServiceSource.URL)
Elsewhere in your code.
If I understand your question, the correct method in your enum is to use this like so,
public enum ServiceSource
{
NONE( "no_value" ),
URL( "url" ),
FILE( "file" );
ServiceSource(String v) {
text =v;
}
private String text;
public boolean isURL() {
return this == URL;
}
}
You can make a method on your Enum to check the value of itself like this:
public boolean isURL(){
return (URL == this);
}
But it's hard to see the value in this approach since every Object has a built in equals() method that accomplishes the same thing.
if (serviceSource.equals(ServiceSource.URL)) { ... }
This would be a more common and obvious way to check the assigned value of an Enum variable (or any variable for that matter). Taking the first approach would require you to have a new isX() method on your Enum; every time you add an Enum constant, you would probably want a new method to accompany it.
This seems like a straightforward question, but I can't find it in the Restfulie documentation nor is Google coming up with an example.
I've got a Resource defined, the method is getting invoked, but I need to get to the query parameters on the URL that was used, which presumably means getting to the HttpRequest. Anyone know how you do that with Restfulie?
#Resource
public class Subscribers
{
private final Result result;
public Subscribers(Result result ){
this.result = result;
}
#Get
#Path("/subscribers")
public void get() {
// Need to get at the query parameters here...
result.use( json() ).from( "You got me" ).serialize();
}
}
Try this way
#Get
#Path("/subscribers")
public void get(#QueryParam("name") String name) {
}
your have to append the keys and values to the request URL. also you need to encode the values.
http://mydomain/subscribers?name=abcde
When I try to give a value to my enum, it gives me this error:
constructor status in enum status cannot be applied to given types; STATUS_OPEN(0),
Why is this happening and how do I fix it?
Here is my code thus far:
public enum Status
{
STATUS_OPEN(0),
STATUS_STARTED(1),
STATUS_INPROGRESS(2),
STATUS_ONHOLD(3),
STATUS_COMPLETED(4),
STATUS_CLOSED(5);
}
I'm using notepad and the JDK via command prompt - I don't want to use netbeans or eclipse at the moment.
I was following this site: link
I've googled around and I couldn't really find why this issue is occurring or how to fix it by searching for the error.
You need to add a constructor to the enum.
public enum Status {
STATUS_OPEN(0),
STATUS_STARTED(1),
STATUS_INPROGRESS(2),
STATUS_ONHOLD(3),
STATUS_COMPLETED(4),
STATUS_CLOSED(5);
private final int number;
Status(int number) {
this.number = number;
}
public int getMagicNumber() { return number; }
}
This'll fix your syntax problems, but what are you hoping to achieve with the number? Enums are often used instead of the need for numbers at all.
you need to declare the status instance variable and constructor. like this
public enum Status
{
STATUS_OPEN(0),
STATUS_STARTED(1),
STATUS_INPROGRESS(2),
STATUS_ONHOLD(3),
STATUS_COMPLETED(4),
STATUS_CLOSED(5);
private int status;
private Status(int status){
this.status = status;
}
public int getStatus(){
return this.status;
}
}