Java enum giving an error? - java

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;
}
}

Related

Method returning alternative data structures based on execution result

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.

Can I make a constructor for a custom annotation?

I am trying to make an annotation for different methods and classes to programmatically keep track of all the rules, so I can display them to the user.
I would like the annotation class Rule to record all the places that the annotation is used. As a first step, I tried adding a single static counter to the class, here's what the Rule annotation looks like:
public #interface Rule {
static int count = 0;
String name();
String description(); //Note the parentheses
public Rule(String name, String description) {
count++;
this.name = name;
this.description = description;
}
}
The way I would use it is like this:
public class Airline {
private String code;
#Rule(name = "Formatted Code", description = "e.g. Format 'la' as 'LA'")
public String codeFormatted() {
return code.toUpperCase();
}
public static void main(String args[]) {
System.out.println(Rule.count);
}
}
Without the Rule public constructor, this compiles using javac version 1.8.0_162.
When I add the public constructor (to increment Rule.count), I get compiler errors:
javac Rule.java
Rule.java:6: error: <identifier> expected
public Rule(String name, String description) {
^
1 error
Compilation exited abnormally with code 1 at Thu Mar 22 19:58:39
What am I missing in my Rule constructor?
Or, is this a completely ridiculous idea and I should feel bad? I can't tell, still getting used to annotations.

Java enum: Return value other than String

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.

How do you modify IDEA IntelliJ v10.x code generators for getters and setters?

IntelliJ generates the following getter/setter code for boolean fields:
private boolean isTest;
public boolean isTest() {
return isTest;
}
public void setTest(boolean test) {
isTest = test;
}
This too yields the same method signatures:
private boolean test;
public boolean isTest() {
return test;
}
public void setTest(boolean test) {
this.test = test;
}
Great! So far so good. IntelliJ is following JavaBean naming conventions for boolean.
But watch what happens when you use the object Boolean (instead of the primitive boolean):
private Boolean isTest;
public Boolean getTest() {
return isTest;
}
public void setTest(Boolean test) {
isTest = test;
}
Uh oh! Do you see it? It should be generating this instead (which Eclipse does):
private Boolean isTest;
public Boolean getIsTest() {
return isTest;
}
public void setIsTest(Boolean isTest) {
isTest = isTest;
}
This may seem like no big deal, but this little inconsistency caused a huge project nightmare. The reason is this: There are other layers and frameworks which expect to map variables EXACTLY to the Java class field names - otherwise it fails without custom mapping logic (painful and unnecessary).
Our team uses the is*Name* pattern for all Boolean objects. Even our boolean database columns are named is_name, which gets translated to "is*Name*" using JBoss Hibernate reverse engineering tools plugin for Eclipse.
Does anyone know how to fix this? Is there some type of code generation template we can configure? Any help is greatly appreciated.
It was reported that Eclipse generates get<Property> for Boolean while IDEA generated is<Property>. It is against the specification and users requested to fix it.
As a result of addressing this bug current IDEA version is working in accordance to the JavaBeans specification and uses such getters only for primitive boolean type and get<Property> for other types including Boolean.
Sorry, but there is no way to configure this behavior in IDEA.

XML to Java Object

I am trying to convert an XML file to a Java Object, now, I have read of JAXB, XStream, Sax and DOM, I'd like to convert this sort of type of xml:
<testxml testtype="converting" duration="100.00" status="successful" />
it might be as well as:
<testxml testype="converting" duration="100.00"> successful </textxml>
I wanted to know if there is anything out there (and possibly not 3rd party) that I can use, without declaring a template in DTD or in JAXB in XSD but Java (therefore I will declare a java class called testxml with all the relevant variable i.e. testtype, duration, status>
Thank you all for your time.
The class below using JAXB Annotations will do exactly what you need, no need to create an XSD or a template using Java 1.6+:
#XmlRootElement
public class TestXML {
private String testtype;
private double duration;
private String status;
public void setTesttype(String testtype) {
this.testtype = testtype;
}
#XmlAttribute
public String getTesttype() {
return testtype;
}
public void setDuration(double duration) {
this.duration = duration;
}
#XmlAttribute
public double getDuration() {
return duration;
}
public void setStatus(String status) {
this.status = status;
}
#XmlValue
public String getStatus() {
return status;
}
public static void main(String args[]) {
TestXML test = JAXB.unmarshal(new File("test.xml"), TestXML.class);
System.out.println("testtype = " + test.getTesttype());
System.out.println("duration = " + test.getDuration());
System.out.println("status = " + test.getStatus());
}
}
Using this as test.xml:
<testxml testtype="converting" duration="100.00"> successful </testxml>
You can do this pretty simply by using java.xml.bind.annotations on a Java class and JAXB.Unmarshal
JAXB is part of the JRE in java 1.6+
Try XStream/XPP3. That's good stuff. Takes a couple of hours to figure out. Does all the magic for you.
Personally I use XStream # http://x-stream.github.io/ It's really easy to use and still offers enough features in case you need them. Unfortunately it looks like the project is not actively maintained anymore, but I haven't seen an alternative so far that suits my needs as well. I'd say it's worth spending a bit of time to check it out ;-)
edit: when you can use Java 6, I completely agree the other answers are preferable!

Categories