Java Custom enum - java

I have a table and want to save the status using a enum. I created a enum as below
/**
* Enumeration for Status
*
*
* Current defined values are :
* <ul>
* <li>ACTIVE = 1</li>
* <li>INACTIVE = 2</li>
* </ul>
*/
public enum Status {
/**
* ACTIVE (Ordinal 1).
*/
ACTIVE(1),
/**
* INACTIVE (Ordinal 2).
*/
INACTIVE(2),
private int value;
private Status(int value) {
this.value = value;
}
public static void main (String ars[]){
for (Status str : Status.values()) {
System.out.println("====str==========="+str.name() +"::::::: "+str.ordinal());
}
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
How to I get the ordinal value from 1. My output is like this
====str===========ACTIVE::::::: 0
====str===========INACTIVE::::::: 1
Actually i have mapped this enum to my Entity and i have used it as below
#Column(name = "STATUS",nullable=false)
#Enumerated(EnumType.ORDINAL)
private Status status;
How to i save the Active status as 1 ... ?

You could override the toString() method of your enum or provide a getter.
public enum Status {
/**
* ACTIVE (Ordinal 1).
*/
ACTIVE(1),
/**
* INACTIVE (Ordinal 2).
*/
INACTIVE(2); // Note the semicolon
private final int value;
private Status(int value) {
this.value = value;
}
public int getValue() {
return value;
}
// OR
#Override
public String toString() {
return String.valueOf(value);
}
}
Then you can call
System.out.println(ACTIVE); // toString is called
or
System.out.println(ACTIVE.getValue());

Use getValue() instead of ordinal()? ordinal() doesn't magically know to call your method, it just returns the ordinal.

print str.getValue().
ordinal gives you default values.

Related

Syntax with Java on Enumerators

This is the question given:
This is my attempt:
class SerialPublication {
public enum Frequency {DAILY, WEEKLY, MONTHLY, QUARTERLY, YEARLY, UNDEFINED}
protected Frequency frequency;
public SerialPublication(){
frequency = Frequency.UNDEFINED;
}
public SerialPublication(String freq){
setFrequency(freq);
}
public void setFrequency(Frequency freq){
this.frequency = freq;
}
public Frequency getFrequency(){
return frequency;
}
}
This is my error message:
We are told not to add the first "public" in the class declaration because of the way the website works.
I'm not very familiar with the syntax behind enumerators (and I'm quite new to java too) so I'm not entirely sure what I'm doing wrong. Any help would be appreciated.
you forgot the type Frequency in this method setFrequency here:
public void setFrequency(freq){
frequency = Frequency.freq;
}
it must be:
public void setFrequency( Frequency freq){
this.frequency = freq;
}
You will also need to build the enum from any given String. See the inner enum class fromString(String aFrequency). As a bonus, the examply also shows you can add extra information to an enum.
public class SerialPublication {
public enum Frequency {
//Can add extra information to enums
DAILY("Daily"),
WEEKLY("Weekly"),
MONTHLY("Monthly"),
QUARTERLY("Quarterly"),
YEARLY("Yearly"),
UNDEFINED("Undefined");
private final String frequency;
Frequency(String frequency) {
this.frequency = frequency;
}
public String getFrequency() {
return frequency;
}
/**
* Builds an enum from a given frequency string
* #param aFrequency
* #return
*/
public static Frequency fromString(String aFrequency) {
for (Frequency frequency : Frequency.values()) {
if(frequency.getFrequency().toLowerCase().equals(aFrequency.toLowerCase())) {
return frequency;
}
}
return Frequency.UNDEFINED; //Could send null back
}
}
private Frequency frequency;
public SerialPublication(){
frequency = Frequency.UNDEFINED;
}
public SerialPublication(String freq){
this.setFrequency(freq);
}
/**
* Sets the frequence based on a String. This handles invalid input by assuming nonsense equals undefined
* #param frequency
*/
public void setFrequency(String frequency){
this.setFrequency(Frequency.fromString(frequency));
}
/**
* Sets the frequency based on the Frequency Enum.
* #param frequency
*/
public void setFrequency(Frequency frequency) {
this.frequency = frequency;
}
public Frequency getFrequency(){
return frequency;
}
public static void main(String[] args) {
SerialPublication publication = new SerialPublication();
System.out.println(publication.getFrequency());
publication.setFrequency("monthly");
System.out.println(publication.getFrequency());
publication.setFrequency(Frequency.QUARTERLY);
System.out.println(publication.getFrequency());
publication.setFrequency("cows are great");
System.out.println(publication.getFrequency());
}
}

How to invoke ParkingTicket(parker, parkee)?

Here is my problem I can't seem to figure out how to invoke a ParkingTicket object if (carMinutesPaid>meterMinutesPaid)? can any one help here are the details below to the question.
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
System.out.println("null");
}
return new ParkingTicket(parker, parkee);
}
Here is the question for my project.
Remember, this method must be able to be used without a ParkingTicket object in existence.
Using a Car parameter and a ParkingMeter parameter, decide whether a ParkingTicket object should be created.
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and return the result.
Return null if a ticket was not merited.
Here is my car class:
/**
* This is a Car class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class Car
{
private static final int MINIMUM_PLATE_LENGTH=2;
private static final int MAXIMUM_PLATE_LENGTH=7;
public static final char MANUAL_TRANSMISSION='m';
public static final char AUTOMATIC_TRANSMISSION='a';
private static int defaultMinutesParked = 0;
private static double defaultOdometerInKm = 50000.5;
private String licensePlate;
private char transmissionType;
private double odometerInKm;
private int minutesParked;
/**
* #param newProposedLicensePlate the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public Car(String newProposedLicensePlate)
{
setLicensePlate(newProposedLicensePlate);
transmissionType = AUTOMATIC_TRANSMISSION;
odometerInKm = defaultOdometerInKm;
minutesParked = defaultMinutesParked;
}
/**
* #return the license plate of the car can equal null
* but must be between MINIMUM_PLATE_LENGTH and MAXIMUM_PLATE_LENGTH
*/
public String getLicensePlate()
{
return licensePlate;
}
/**
* #return the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
*/
public char getTransmissionType()
{
return transmissionType;
}
/**
* #return the odometer in kilometers
*/
public double getOdometerInKm()
{
return odometerInKm;
}
/**
* Recieve the license plate
* Mutator.licensePlate.
* #param proposedLicense String Conforming to ICBC *length* guidlines:
* http://www.icbc.com/vehicle-registration/license-plates/Pages/Personalized-licence-plates.aspx
* May also be null. The null represents a car without a plate
* If validation fails, null will be set.
*/
public void setLicensePlate(String proposedLicense)
{
if(proposedLicense==null){
licensePlate = proposedLicense;
}
else if(proposedLicense.length()>=MINIMUM_PLATE_LENGTH && proposedLicense.length()<=MAXIMUM_PLATE_LENGTH){
licensePlate = proposedLicense;
}
else{
licensePlate = null;
}
}
/**
* #param mOrA recieve the transmission type MANUAL_TRANSMISSION or AUTOMATIC_TRANSMISSION
* if invalid type of transmission is entered then will return "Installation failure: 'mOrA' is not a vaild transmission type"
*/
public void setTransmissionType(char mOrA)
{
if(mOrA==MANUAL_TRANSMISSION){
transmissionType = mOrA;
}
else if(mOrA==AUTOMATIC_TRANSMISSION){
transmissionType = mOrA;
}
else if (mOrA==mOrA){
System.out.println("Installation failure:" + " " + ("'")+(mOrA)+("'") + " " + "is not a valid transmission type.");
}
else{
transmissionType = mOrA;
}
}
/**
* #return the value of the odometer in with the String kilometers
*/
public String readOdometer()
{
return odometerInKm + " " + "kilometers";
}
/**
* #return the false if the minutesParked equals zero; otherwise true
*/
public boolean isParked()
{
if(minutesParked==defaultMinutesParked){
return false;
}
else{
return true;
}
}
/**
* #param duration replaces any existing value in minutesParked with the value from duration
*/
public void park(int duration)
{
if(duration>=defaultMinutesParked){
minutesParked = duration;
}
}
/**
* #param aOdometerInKm recieve the odometer in kilometers
*/
public void setOdometerInKm(double aOdometerInKm)
{
odometerInKm = aOdometerInKm;
}
/**
* #param aMinutesParked recieve the minutes parked in the stall but can not be a negative number
* if invalid number of minutes is entered then the number of minutes will not change.
*/
public void setMinutesParked(int aMinutesParked)
{
if(aMinutesParked>=defaultMinutesParked){
minutesParked = aMinutesParked;
}
else{
return;
}
}
/**
* #return the minutes parked
*/
public int getMinutesParked()
{
return minutesParked;
}
}
here is my ParkingMeter class:
/**
* This is a ParkingMeter class for Impark.
*
* #author Tre
* #version 2.0 15 October 2015
*/
public class ParkingMeter
{
private int minutesPaid;
private String methodPaid;
/**
* #param newMinutesPaid the minutes paid for parking meter
*/
public ParkingMeter()
{
}
/**
* #return the minutes paid
*/
public int getMinutesPaid()
{
return minutesPaid;
}
/**
* #return the method paid
*/
public String getMethodPaid()
{
return methodPaid;
}
/**
* #param paidBy the payment method customer will paid by
*/
public void setMethodPaid(String paidBy) /* BONUS for creating method paid */
{
if(methodPaid=="Visa"){
methodPaid = paidBy;
}
else if(methodPaid=="Master Card"){
methodPaid = paidBy;
}
else if(methodPaid=="American Express"){
methodPaid = paidBy;
}
else if(methodPaid=="Cash"){
methodPaid = paidBy;
}
else if(methodPaid=="Debit"){
methodPaid = paidBy;
}
else{
methodPaid = paidBy;
}
}
/**
* #param quantity the added minutes paid must not have a negative number
*/
public void addMinutesPaid(int quantity)
{
if(quantity>=0){
minutesPaid+=quantity;
}
}
}
and here is my ParkingTicket class:
/**
* This is a ParkingTicket class for Impark.
*
* #author Tre
* #version 1.0
*/
public class ParkingTicket
{
private final String referenceNumber;
private static String carLicensePlate;
private static int carMinutesParked;
private static int meterMinutesPaid;
private static int count = 1000;
private static String PREFIX = "V";
/**
* #param recorededLicense the value of the tick number
*/
private ParkingTicket(String recordedLicense, int newCarMinutesParked, int newMeterPaidMinutes)
{
referenceNumber = (PREFIX+count++);
carMinutesParked = newCarMinutesParked;
meterMinutesPaid = newMeterPaidMinutes;
}
/**
* #param
*/
private ParkingTicket(Car parker, ParkingMeter parkee)
{
this(parker.getLicensePlate(), parker.getMinutesParked(), parkee.getMinutesPaid());
}
/**
* #return referenceNumber the reference number
*/
public String getReferenceNumber()
{
return referenceNumber;
}
/**
* #return carLicensePlate the car's license plate
*/
public String getCarLicensePlate()
{
return carLicensePlate;
}
/**
* #return carMinutesParked the minutes car was parked
*/
public int getCarMinutesParked()
{
return carMinutesParked;
}
/**
* #return meterMinutesPaid the minutes paid on meter
*/
public int getMeterMinutesPaid()
{
return meterMinutesPaid;
}
/**
* #return count the with initial value of 1000
*/
public int getCount()
{
return count;
}
public static ParkingTicket checkParking(int carMinutesParked, int meterMinutesPaid)
{
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
if(carMinutesParked>meterMinutesPaid){
return new ParkingTicket(parker, parkee);
}
else if(carMinutesParked<=meterMinutesPaid){
return null;
}
return new ParkingTicket(parker, parkee);
}
}
This requirement:
Using a Car parameter and a ParkingMeter parameter, decide whether a
ParkingTicket object should be created.
suggests that you provide two parameters to the checkParking method, one is of the type Car and one of the ParkingMeter. So it should be like so:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
This code :
Car parker = carMinutesParked;
ParkingMeter parkee = parkee;
won't even compile
line 1: you're trying to assign int to object - that's called type mismatch.
line 2: variable parkee is not declared anywhere (except for the headline of the question).
You see, only the Car object holds the information about the parking duration, and you need the object for creating parking ticket. Same for the ParkingMeter
It should be vice versa - you get the values from the objects:
int carMinutesParked = car.getMinutesParked();
int meterMinutesPaid = meter.getMinutesPaid();
and proceed from here with if( or even use it in if without declaring temporary variables).
This one:
Invoke ParkingTicket(parker, parkee) if a ticket was merited, and
return the result.
you did OK.
Now this requirement:
Return null if a ticket was not merited.
suggest the method will return null, not string that equals to "null" .
So, based on these requirements it should rather be:
public static ParkingTicket checkParking(Car car, ParkingMeter meter)
{
//sanity check (bonus)
if ((car == null) || (meter == null))
return null;
if(car.getMinutesParked() > meter.getMinutesPaid()){
return new ParkingTicket(car, meter);
}
return null;
}
Note however, I don't know if you need any additional logic in this code and don't suggest this should be your final version, just explaining the general approach.

Type mismatch in key from map

I'm getting this error:
java.lang.Exception: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.LongWritable
at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462)
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:522)
Caused by: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.LongWritable
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:1074)
at org.apache.hadoop.mapred.MapTask$NewOutputCollector.write(MapTask.java:715)
at org.apache.hadoop.mapreduce.task.TaskInputOutputContextImpl.write(TaskInputOutputContextImpl.java:89)
at org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.write(WrappedMapper.java:112)
at org.apache.hadoop.mapreduce.Mapper.map(Mapper.java:125)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:146)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:243)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
from this code:
public class MyAvroApplication {
private static class MyReducer extends Reducer<Email, Text, Text, Text> {
private Text from = new Text();
private Text subject = new Text();
public void reduce(Email key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
from.set(key.getFrom().toString());
subject.set(key.getSubject().toString());
context.write(from, subject);
}
}
private static class MyAvroMapper extends Mapper<Text, Email, Email, Text> {
protected void map(Email email, NullWritable value, Context context) throws IOException, InterruptedException {
context.write(email,
new Text(email.getSubject().toString()));
}
}
public static void main(String[] args) throws Exception {
UserGroupInformation ugi = UserGroupInformation.createRemoteUser("hdfs");
ugi.doAs(new PrivilegedExceptionAction<Void>() {
public Void run() throws Exception {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://127.0.0.1:8020/user/rich");
conf.set("hadoop.job.ugi", "hdfs");
Job job = Job.getInstance(conf, "mytest");
AvroJob.setInputKeySchema(job, Email.getClassSchema());
AvroJob.setOutputKeySchema(job, Email.getClassSchema());
job.setJarByClass(MyApplication.class);
job.setMapperClass(MyAvroMapper.class);
job.setCombinerClass(MyReducer.class);
job.setReducerClass(MyReducer.class);
// job.setInputFormatClass(AvroKeyInputFormat.class);
// job.setOutputFormatClass(AvroKeyOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path("/user/rich/in/"));
FileOutputFormat.setOutputPath(job, new Path("/user/rich/out/"));
boolean result = job.waitForCompletion(true);
System.out.println(result);
return null;
}
});
}
}
I'm really struggling to understand how to match up the various key-value parameters on the way in and out everywhere. My intention is to read some Avro format files in as an Email and then run some simple calculations, just counting the number of emails would be a good start.
Edit:
A similar error occurs with this Mapper:
private static class MyAvroMapper extends Mapper<Text, AvroKey<Email>, AvroKey<Email>, Text> {
protected void map(Text key, AvroKey<Email> email, Context context) throws IOException, InterruptedException {
context.write(email,
new Text(email.datum().getSubject().toString()));
}
}
And the error:
java.lang.Exception: java.lang.ClassCastException: org.apache.hadoop.io.LongWritable cannot be cast to org.apache.hadoop.io.Text
at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462)
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:522)
Caused by: java.lang.ClassCastException: org.apache.hadoop.io.LongWritable cannot be cast to org.apache.hadoop.io.Text
at com.test.myapp.MyAvroApplication$MyAvroMapper.map(MyAvroApplication.java:1)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:146)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:243)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
The Email class generated from the schema:
#SuppressWarnings("all")
#org.apache.avro.specific.AvroGenerated
public class Email extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"Email\",\"namespace\":\"com.test.myapp.avro\",\"fields\":[{\"name\":\"message_id\",\"type\":[\"null\",\"string\"],\"doc\":\"\"},{\"name\":\"date\",\"type\":[\"long\",\"null\"]},{\"name\":\"from\",\"type\":{\"type\":\"record\",\"name\":\"EmailAddress\",\"fields\":[{\"name\":\"name\",\"type\":[\"null\",\"string\"],\"doc\":\"\"},{\"name\":\"address\",\"type\":[\"null\",\"string\"],\"doc\":\"\"}]}},{\"name\":\"subject\",\"type\":[\"string\",\"null\"]},{\"name\":\"body\",\"type\":[\"string\",\"null\"]},{\"name\":\"tos\",\"type\":[\"null\",{\"type\":\"array\",\"items\":[\"null\",\"EmailAddress\"]}],\"doc\":\"\"},{\"name\":\"ccs\",\"type\":[\"null\",{\"type\":\"array\",\"items\":[\"null\",\"EmailAddress\"]}],\"doc\":\"\"},{\"name\":\"bccs\",\"type\":[\"null\",{\"type\":\"array\",\"items\":[\"null\",\"EmailAddress\"]}],\"doc\":\"\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
/** */
#Deprecated public java.lang.CharSequence message_id;
#Deprecated public java.lang.Long date;
#Deprecated public com.test.myapp.avro.EmailAddress from;
#Deprecated public java.lang.CharSequence subject;
#Deprecated public java.lang.CharSequence body;
/** */
#Deprecated public java.util.List<com.test.myapp.avro.EmailAddress> tos;
/** */
#Deprecated public java.util.List<com.test.myapp.avro.EmailAddress> ccs;
/** */
#Deprecated public java.util.List<com.test.myapp.avro.EmailAddress> bccs;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public Email() {}
/**
* All-args constructor.
*/
public Email(java.lang.CharSequence message_id, java.lang.Long date, com.test.myapp.avro.EmailAddress from, java.lang.CharSequence subject, java.lang.CharSequence body, java.util.List<com.test.myapp.avro.EmailAddress> tos, java.util.List<com.test.myapp.avro.EmailAddress> ccs, java.util.List<com.test.myapp.avro.EmailAddress> bccs) {
this.message_id = message_id;
this.date = date;
this.from = from;
this.subject = subject;
this.body = body;
this.tos = tos;
this.ccs = ccs;
this.bccs = bccs;
}
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return message_id;
case 1: return date;
case 2: return from;
case 3: return subject;
case 4: return body;
case 5: return tos;
case 6: return ccs;
case 7: return bccs;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
#SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: message_id = (java.lang.CharSequence)value$; break;
case 1: date = (java.lang.Long)value$; break;
case 2: from = (com.test.myapp.avro.EmailAddress)value$; break;
case 3: subject = (java.lang.CharSequence)value$; break;
case 4: body = (java.lang.CharSequence)value$; break;
case 5: tos = (java.util.List<com.test.myapp.avro.EmailAddress>)value$; break;
case 6: ccs = (java.util.List<com.test.myapp.avro.EmailAddress>)value$; break;
case 7: bccs = (java.util.List<com.test.myapp.avro.EmailAddress>)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'message_id' field.
* */
public java.lang.CharSequence getMessageId() {
return message_id;
}
/**
* Sets the value of the 'message_id' field.
* * #param value the value to set.
*/
public void setMessageId(java.lang.CharSequence value) {
this.message_id = value;
}
/**
* Gets the value of the 'date' field.
*/
public java.lang.Long getDate() {
return date;
}
/**
* Sets the value of the 'date' field.
* #param value the value to set.
*/
public void setDate(java.lang.Long value) {
this.date = value;
}
/**
* Gets the value of the 'from' field.
*/
public com.test.myapp.avro.EmailAddress getFrom() {
return from;
}
/**
* Sets the value of the 'from' field.
* #param value the value to set.
*/
public void setFrom(com.test.myapp.avro.EmailAddress value) {
this.from = value;
}
/**
* Gets the value of the 'subject' field.
*/
public java.lang.CharSequence getSubject() {
return subject;
}
/**
* Sets the value of the 'subject' field.
* #param value the value to set.
*/
public void setSubject(java.lang.CharSequence value) {
this.subject = value;
}
/**
* Gets the value of the 'body' field.
*/
public java.lang.CharSequence getBody() {
return body;
}
/**
* Sets the value of the 'body' field.
* #param value the value to set.
*/
public void setBody(java.lang.CharSequence value) {
this.body = value;
}
/**
* Gets the value of the 'tos' field.
* */
public java.util.List<com.test.myapp.avro.EmailAddress> getTos() {
return tos;
}
/**
* Sets the value of the 'tos' field.
* * #param value the value to set.
*/
public void setTos(java.util.List<com.test.myapp.avro.EmailAddress> value) {
this.tos = value;
}
/**
* Gets the value of the 'ccs' field.
* */
public java.util.List<com.test.myapp.avro.EmailAddress> getCcs() {
return ccs;
}
/**
* Sets the value of the 'ccs' field.
* * #param value the value to set.
*/
public void setCcs(java.util.List<com.test.myapp.avro.EmailAddress> value) {
this.ccs = value;
}
/**
* Gets the value of the 'bccs' field.
* */
public java.util.List<com.test.myapp.avro.EmailAddress> getBccs() {
return bccs;
}
/**
* Sets the value of the 'bccs' field.
* * #param value the value to set.
*/
public void setBccs(java.util.List<com.test.myapp.avro.EmailAddress> value) {
this.bccs = value;
}
/** Creates a new Email RecordBuilder */
public static com.test.myapp.avro.Email.Builder newBuilder() {
return new com.test.myapp.avro.Email.Builder();
}
/** Creates a new Email RecordBuilder by copying an existing Builder */
public static com.test.myapp.avro.Email.Builder newBuilder(com.test.myapp.avro.Email.Builder other) {
return new com.test.myapp.avro.Email.Builder(other);
}
/** Creates a new Email RecordBuilder by copying an existing Email instance */
public static com.test.myapp.avro.Email.Builder newBuilder(com.test.myapp.avro.Email other) {
return new com.test.myapp.avro.Email.Builder(other);
}
/**
* RecordBuilder for Email instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<Email>
implements org.apache.avro.data.RecordBuilder<Email> {
private java.lang.CharSequence message_id;
private java.lang.Long date;
private com.test.myapp.avro.EmailAddress from;
private java.lang.CharSequence subject;
private java.lang.CharSequence body;
private java.util.List<com.test.myapp.avro.EmailAddress> tos;
private java.util.List<com.test.myapp.avro.EmailAddress> ccs;
private java.util.List<com.test.myapp.avro.EmailAddress> bccs;
/** Creates a new Builder */
private Builder() {
super(com.test.myapp.avro.Email.SCHEMA$);
}
/** Creates a Builder by copying an existing Builder */
private Builder(com.test.myapp.avro.Email.Builder other) {
super(other);
if (isValidValue(fields()[0], other.message_id)) {
this.message_id = data().deepCopy(fields()[0].schema(), other.message_id);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.date)) {
this.date = data().deepCopy(fields()[1].schema(), other.date);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.from)) {
this.from = data().deepCopy(fields()[2].schema(), other.from);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.subject)) {
this.subject = data().deepCopy(fields()[3].schema(), other.subject);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.body)) {
this.body = data().deepCopy(fields()[4].schema(), other.body);
fieldSetFlags()[4] = true;
}
if (isValidValue(fields()[5], other.tos)) {
this.tos = data().deepCopy(fields()[5].schema(), other.tos);
fieldSetFlags()[5] = true;
}
if (isValidValue(fields()[6], other.ccs)) {
this.ccs = data().deepCopy(fields()[6].schema(), other.ccs);
fieldSetFlags()[6] = true;
}
if (isValidValue(fields()[7], other.bccs)) {
this.bccs = data().deepCopy(fields()[7].schema(), other.bccs);
fieldSetFlags()[7] = true;
}
}
/** Creates a Builder by copying an existing Email instance */
private Builder(com.test.myapp.avro.Email other) {
super(com.test.myapp.avro.Email.SCHEMA$);
if (isValidValue(fields()[0], other.message_id)) {
this.message_id = data().deepCopy(fields()[0].schema(), other.message_id);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.date)) {
this.date = data().deepCopy(fields()[1].schema(), other.date);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.from)) {
this.from = data().deepCopy(fields()[2].schema(), other.from);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.subject)) {
this.subject = data().deepCopy(fields()[3].schema(), other.subject);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.body)) {
this.body = data().deepCopy(fields()[4].schema(), other.body);
fieldSetFlags()[4] = true;
}
if (isValidValue(fields()[5], other.tos)) {
this.tos = data().deepCopy(fields()[5].schema(), other.tos);
fieldSetFlags()[5] = true;
}
if (isValidValue(fields()[6], other.ccs)) {
this.ccs = data().deepCopy(fields()[6].schema(), other.ccs);
fieldSetFlags()[6] = true;
}
if (isValidValue(fields()[7], other.bccs)) {
this.bccs = data().deepCopy(fields()[7].schema(), other.bccs);
fieldSetFlags()[7] = true;
}
}
/** Gets the value of the 'message_id' field */
public java.lang.CharSequence getMessageId() {
return message_id;
}
/** Sets the value of the 'message_id' field */
public com.test.myapp.avro.Email.Builder setMessageId(java.lang.CharSequence value) {
validate(fields()[0], value);
this.message_id = value;
fieldSetFlags()[0] = true;
return this;
}
/** Checks whether the 'message_id' field has been set */
public boolean hasMessageId() {
return fieldSetFlags()[0];
}
/** Clears the value of the 'message_id' field */
public com.test.myapp.avro.Email.Builder clearMessageId() {
message_id = null;
fieldSetFlags()[0] = false;
return this;
}
/** Gets the value of the 'date' field */
public java.lang.Long getDate() {
return date;
}
/** Sets the value of the 'date' field */
public com.test.myapp.avro.Email.Builder setDate(java.lang.Long value) {
validate(fields()[1], value);
this.date = value;
fieldSetFlags()[1] = true;
return this;
}
/** Checks whether the 'date' field has been set */
public boolean hasDate() {
return fieldSetFlags()[1];
}
/** Clears the value of the 'date' field */
public com.test.myapp.avro.Email.Builder clearDate() {
date = null;
fieldSetFlags()[1] = false;
return this;
}
/** Gets the value of the 'from' field */
public com.test.myapp.avro.EmailAddress getFrom() {
return from;
}
/** Sets the value of the 'from' field */
public com.test.myapp.avro.Email.Builder setFrom(com.test.myapp.avro.EmailAddress value) {
validate(fields()[2], value);
this.from = value;
fieldSetFlags()[2] = true;
return this;
}
/** Checks whether the 'from' field has been set */
public boolean hasFrom() {
return fieldSetFlags()[2];
}
/** Clears the value of the 'from' field */
public com.test.myapp.avro.Email.Builder clearFrom() {
from = null;
fieldSetFlags()[2] = false;
return this;
}
/** Gets the value of the 'subject' field */
public java.lang.CharSequence getSubject() {
return subject;
}
/** Sets the value of the 'subject' field */
public com.test.myapp.avro.Email.Builder setSubject(java.lang.CharSequence value) {
validate(fields()[3], value);
this.subject = value;
fieldSetFlags()[3] = true;
return this;
}
/** Checks whether the 'subject' field has been set */
public boolean hasSubject() {
return fieldSetFlags()[3];
}
/** Clears the value of the 'subject' field */
public com.test.myapp.avro.Email.Builder clearSubject() {
subject = null;
fieldSetFlags()[3] = false;
return this;
}
/** Gets the value of the 'body' field */
public java.lang.CharSequence getBody() {
return body;
}
/** Sets the value of the 'body' field */
public com.test.myapp.avro.Email.Builder setBody(java.lang.CharSequence value) {
validate(fields()[4], value);
this.body = value;
fieldSetFlags()[4] = true;
return this;
}
/** Checks whether the 'body' field has been set */
public boolean hasBody() {
return fieldSetFlags()[4];
}
/** Clears the value of the 'body' field */
public com.test.myapp.avro.Email.Builder clearBody() {
body = null;
fieldSetFlags()[4] = false;
return this;
}
/** Gets the value of the 'tos' field */
public java.util.List<com.test.myapp.avro.EmailAddress> getTos() {
return tos;
}
/** Sets the value of the 'tos' field */
public com.test.myapp.avro.Email.Builder setTos(java.util.List<com.test.myapp.avro.EmailAddress> value) {
validate(fields()[5], value);
this.tos = value;
fieldSetFlags()[5] = true;
return this;
}
/** Checks whether the 'tos' field has been set */
public boolean hasTos() {
return fieldSetFlags()[5];
}
/** Clears the value of the 'tos' field */
public com.test.myapp.avro.Email.Builder clearTos() {
tos = null;
fieldSetFlags()[5] = false;
return this;
}
/** Gets the value of the 'ccs' field */
public java.util.List<com.test.myapp.avro.EmailAddress> getCcs() {
return ccs;
}
/** Sets the value of the 'ccs' field */
public com.test.myapp.avro.Email.Builder setCcs(java.util.List<com.test.myapp.avro.EmailAddress> value) {
validate(fields()[6], value);
this.ccs = value;
fieldSetFlags()[6] = true;
return this;
}
/** Checks whether the 'ccs' field has been set */
public boolean hasCcs() {
return fieldSetFlags()[6];
}
/** Clears the value of the 'ccs' field */
public com.test.myapp.avro.Email.Builder clearCcs() {
ccs = null;
fieldSetFlags()[6] = false;
return this;
}
/** Gets the value of the 'bccs' field */
public java.util.List<com.test.myapp.avro.EmailAddress> getBccs() {
return bccs;
}
/** Sets the value of the 'bccs' field */
public com.test.myapp.avro.Email.Builder setBccs(java.util.List<com.test.myapp.avro.EmailAddress> value) {
validate(fields()[7], value);
this.bccs = value;
fieldSetFlags()[7] = true;
return this;
}
/** Checks whether the 'bccs' field has been set */
public boolean hasBccs() {
return fieldSetFlags()[7];
}
/** Clears the value of the 'bccs' field */
public com.test.myapp.avro.Email.Builder clearBccs() {
bccs = null;
fieldSetFlags()[7] = false;
return this;
}
#Override
public Email build() {
try {
Email record = new Email();
record.message_id = fieldSetFlags()[0] ? this.message_id : (java.lang.CharSequence) defaultValue(fields()[0]);
record.date = fieldSetFlags()[1] ? this.date : (java.lang.Long) defaultValue(fields()[1]);
record.from = fieldSetFlags()[2] ? this.from : (com.test.myapp.avro.EmailAddress) defaultValue(fields()[2]);
record.subject = fieldSetFlags()[3] ? this.subject : (java.lang.CharSequence) defaultValue(fields()[3]);
record.body = fieldSetFlags()[4] ? this.body : (java.lang.CharSequence) defaultValue(fields()[4]);
record.tos = fieldSetFlags()[5] ? this.tos : (java.util.List<com.test.myapp.avro.EmailAddress>) defaultValue(fields()[5]);
record.ccs = fieldSetFlags()[6] ? this.ccs : (java.util.List<com.test.myapp.avro.EmailAddress>) defaultValue(fields()[6]);
record.bccs = fieldSetFlags()[7] ? this.bccs : (java.util.List<com.test.myapp.avro.EmailAddress>) defaultValue(fields()[7]);
return record;
} catch (Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
}
I think there's a problem in the mapper. When you declare:
private static class MyAvroMapper extends Mapper<Text, Email, Email, Text> {
you're telling hadoop that you're going to expect the couple (Text, Email) as the types of the key and the value of the input and the couple (Email, Text) as the type for key and values of what the mapper will emit (note that are the four types declared as generics for the class.
But when you write a signature like this:
protected void map(Email email, NullWritable value, Context context) throws IOException, InterruptedException {
you're telling hadoop that the key and the value type for the input are Email and NullWritable, hence the exception.

GWT RPC Deferred Binding Failed

We are co-developing a GWT web app that already has working RPC calls for other modules. We built a new RPC module (based on the existing architecture) that compiles and runs, but fails throwing a run-time exception on the following line:
this.dashboardService = GWT.create(DashboardService.class);
The last line in the console is "Uncaught exception escaped" followed by the stack trace to the GWT.create() line above, which is preceded by the console error message:
Deferred binding failed for ... expect subsequent failures [ERROR]
Before those two lines is a laundry list of red errors that begins as follows:
[INFO] [(...)] - Module ... has been loaded
[DEBUG] [(...)] - Rebinding (...).DashboardService
[DEBUG] [(...)] - Invoking generator com.google.gwt.user.rebind.rpc.ServiceInterfaceProxyGenerator
[DEBUG] [(...)] - Generating client proxy for remote service interface '(...).DashboardService'
[INFO] [(...)] - Checking type argument 0 of type 'java.util.Arrays.ArrayList' because it is exposed as an array with a maximum dimension of 1 in this type or one of its subtypes (reached via (...).DashboardChannelSummary)
.
.
.
(more errors without stack trace or line numbers)
The console asks "Did you forget to inherit a module?" but based upon my research, this is not the problem; the problem is somewhere in the GWT deferred binding process, which is not visible in the stack trace. I suspect the bolded line above to be the issue but I cannot make heads or tales of this error message without a line number. Here is the code with proprietary package /module names replaced with (...):
web.xml
<servlet>
<servlet-name>(...) DashboardService
</servlet-name>
<servlet-class>(...).server.DashboardServiceImpl
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>(...) DashboardService
</servlet-name>
<url-pattern>/(...)/DashboardService</url-pattern>
</servlet-mapping>
DashboardChannelSummary.java
/**
* This class is an in memory representation of the results of a document search
*/
public class DashboardChannelSummary implements IsSerializable {
/** Only searches for documents from the past in this amount (the past week) */
private static final int DEFAULT_DASHBOARD_HISTORY_IN_DAYS = -7;
/** array of channels */
private List<Channel> channels;
/** iterator */
private Iterator<Channel> iterator;
/** */
private final static String IMAGE_PATH = "/images/channels/";
/** */
private final static String IMAGE_EXT = ".png";
/** constant for the channel header name */
public final static String BUSINESS_LABEL = "business aviation";
/** constant for the channel header name */
public final static String COMMERCIAL_LABEL = "commercial aviation";
/** constant for the channel header name */
public final static String MRO_LABEL = "mro";
/** constant for the channel header name */
public final static String DEFENSE_LABEL = "defense";
/**
*
*/
public enum CHANNEL_NAME {
BUSINESS (BUSINESS_LABEL, DocumentSummary.BA_ID),
COMMERCIAL (COMMERCIAL_LABEL, DocumentSummary.CA_ID),
MRO (MRO_LABEL, DocumentSummary.MRO_ID),
DEFENSE (DEFENSE_LABEL, DocumentSummary.DEFENSE_ID);
/** */
public String label;
/** */
public int ID;
/** */
private CHANNEL_NAME(String label, int ID) {
this.label = label.toUpperCase();
this.ID = ID;
}
};
/**
*
*/
public static List<String> channelNames() {
ArrayList<String> channels = new ArrayList<String>(CHANNEL_NAME.values().length);
for(int i=0; i<channels.size(); i++) {
channels.add(CHANNEL_NAME.values()[i].label);
}
return channels;
}
/**
*
*/
public static int[] channelIDs() {
int[] IDs = new int[CHANNEL_NAME.values().length];
for(int i=0; i<IDs.length; i++) {
IDs[i] = CHANNEL_NAME.values()[i].ID;
}
return IDs;
}
/**
*
* #return
*/
public static int channelCount() {
return CHANNEL_NAME.values().length;
}
/**
*
*/
public static Date cutoffDate() {
Date date = new Date(0);
CalendarUtil.addDaysToDate(date, DEFAULT_DASHBOARD_HISTORY_IN_DAYS);
return date;
}
/**
*
*/
public class Channel {
/** the name of this channel */
private CHANNEL_NAME name;
/** The list of documents */
private List<DocumentSummary> docs;
/** the iterator */
private Iterator<DocumentSummary> iterator;
/**
*
*/
public Channel(List<DocumentSummary> docs, CHANNEL_NAME name) {
this.docs = docs;
this.name = name;
iterator = docs.iterator();
}
/**
*
*/
public String getLabel() {
return name.label;
}
/**
*
*/
public List<DocumentSummary> getDocuments() {
return docs;
}
/**
*
*/
public boolean hasDocuments() {
return iterator.hasNext();
}
/**
*
* #return
*/
public DocumentSummary nextDocument() {
if(iterator.hasNext()) {
return iterator.next();
}
else {
return null;
}
}
/**
*
*/
public String nextImageURL() {
return GWT.getHostPageBaseURL().concat(IMAGE_PATH + String.valueOf(Random.nextInt(channels.size()) - 1) + IMAGE_EXT);
}
}
/**
* Constructor
*/
public DashboardChannelSummary() {
channels = new ArrayList<Channel>(CHANNEL_NAME.values().length);
iterator = channels.iterator();
}
/**
* Constructor
*/
public DashboardChannelSummary(List<List<DocumentSummary>> channelList) {
channels = new ArrayList<Channel>(CHANNEL_NAME.values().length);
iterator = channels.iterator();
int count = 0;
for(List<DocumentSummary> channelData : channelList)
{
channels.add(new Channel(channelData, CHANNEL_NAME.values()[count++]));
}
}
/**
* #return
*/
public List<Channel> getChannels() {
return channels;
}
/**
* #return
*/
public Channel getChannel(int channel) {
return channels.get(channel);
}
/**
* #return
*/
public Channel nextChannel() {
if(iterator.hasNext()) {
return iterator.next();
}
else {
return null;
}
}
/**
* #return
*/
public List<DocumentSummary> getDocuments(int channel) {
return this.getChannel(channel).getDocuments();
}
}
DashboardPresenter.java:
private final DashboardServiceAsync dashboardService;
and the deferred binding that fails in the Constructor:
this.dashboardService = GWT.create(DashboardService.class);
DashboardServiceAsync.java:
public interface DashboardServiceAsync {
/**
*
* #param channelIDs
* #param startDate
* #param async
*/
void getChannelSummary(int[] channelIDs, Date startDate, AsyncCallback<DashboardChannelSummary> async);
}
DashboardService.java:
#RemoteServiceRelativePath("DashboardService") public interface DashboardService extends RemoteService {
/**
*
* #param channelIDs
* #param startDate
* #return
*/
DashboardChannelSummary getChannelSummary(int[] channelIDs, Date startDate);
}
On the server:
DashboardServiceImpl.java:
public class DashboardServiceImpl extends RemoteServiceServlet implements DashboardService {
/**
*
* #param channelIDs
* #param startDate
* #return
*/
#Override
public DashboardChannelSummary getChannelSummary(int[] channelIDs, Date startDate) {
return new DashboardDaoImpl().getChannelSummary(channelIDs, startDate);
}
}
We have double and triple checked our RPC code for accuracy based on the documentation and the suggestions on SO, such as making sure the method signatures are correct across all interfaces and implementations. Anything obviously wrong jumping out to anyone? Is there a way we can we debug this error with more detail?
UPDATE
DashboardChannelSummary.java redesigned for max efficiency in transporting the data from the server to the client, with all properties now "serializable:"
/**
* This class is an in memory representation of the results of a document search.
*/
public class DashboardChannelSummary implements IsSerializable {
/** Only searches for documents from the past in this amount (the past week) */
private static final int DEFAULT_DASHBOARD_HISTORY_IN_DAYS = -7;
/** array of channels */
private ArrayList<ArrayList<DocumentSummary>> channels;
/** */
private int channel = 0;
/** */
private int image = 0;
/** */
private int index = 0;
/** */
private int last = 0;
/** */
private final static String IMAGE_PATH = "images/channels/";
/** */
private final static String IMAGE_EXT = ".jpg";
/** constant for the channel header name */
public final static String BUSINESS_LABEL = "business";
/** constant for the channel header name */
public final static String COMMERCIAL_LABEL = "commercial";
/** constant for the channel header name */
public final static String MRO_LABEL = "mro";
/** constant for the channel header name */
public final static String DEFENSE_LABEL = "defense";
/**
*
*/
public enum CHANNEL_NAME {
BUSINESS (BUSINESS_LABEL, DocumentSummary.BA_ID, "bus"),
COMMERCIAL (COMMERCIAL_LABEL, DocumentSummary.CA_ID, "_com"),
MRO (MRO_LABEL, DocumentSummary.MRO_ID, "mro"),
DEFENSE (DEFENSE_LABEL, DocumentSummary.DEFENSE_ID, "mil");
/** */
public String label;
/** */
public int ID;
/** */
public String prefix;
/** */
private CHANNEL_NAME(String label, int ID, String prefix) {
this.label = label.toUpperCase();
this.ID = ID;
this.prefix = prefix;
}
};
/**
*
*/
private String nextRandomImage() {
while(index == last) {
index = Random.nextInt(channels.size()) + 1;
}
last = index;
return String.valueOf(index);
}
/**
*
*/
public static List<String> channelNames() {
ArrayList<String> channels = new ArrayList<String>(CHANNEL_NAME.values().length);
for(int i=0; i<channels.size(); i++) {
channels.add(CHANNEL_NAME.values()[i].label);
}
return channels;
}
/**
*
*/
public static int[] channelIDs() {
int[] IDs = new int[CHANNEL_NAME.values().length];
for(int i=0; i<IDs.length; i++) {
IDs[i] = CHANNEL_NAME.values()[i].ID;
}
return IDs;
}
/**
*
* #return
*/
public static int channelCount() {
return CHANNEL_NAME.values().length;
}
/**
*
*/
public static Date cutoffDate() {
Date date = new Date();
CalendarUtil.addDaysToDate(date, DEFAULT_DASHBOARD_HISTORY_IN_DAYS);
return date;
}
/**
* Constructor
*/
public DashboardChannelSummary() {
}
/**
* Constructor
*/
public DashboardChannelSummary(ArrayList<ArrayList<DocumentSummary>> channels) {
this.channels = channels;
}
/**
*
*/
public String nextImageURL() {
if(++image > channels.get(channel - 1).size()) {
image = 0;
}
return GWT.getHostPageBaseURL() +
IMAGE_PATH +
CHANNEL_NAME.values()[channel - 1].prefix +
nextRandomImage() +
IMAGE_EXT;
}
/**
*
*/
public ArrayList<DocumentSummary> nextChannel() {
return channels.get(channel++);
}
/**
*
*/
public String toString() {
return this.getClass().toString() + " current channel : " + channel;
}
}
The culprit is most likely DashboardChannelSummary. To be sure, change the return type of getChannelSummary to something "safe", like String or just Void. If the error persists, there's an issue with the service's configuration (though, I doubt it would come up during GWT's compilation phase). If this service works, then you can be pretty sure that it's because DashboardChannelSummary is not serializable.
While the class itself has a no-args constructor and implements IsSerializable, not all the fields are serializable. You should have a closer look at the Channel class (maybe DocumentSummary too, but there's no code for it provided in the question) and the Iterator fields (ArrayList returns an Itr instance, which doesn't seem to be serializable).
If the error still persists, try simplifying DashboardChannelSummary until you get a working version and then work your way "up", until you find the part that is causing the error.

get enum name from enum value [duplicate]

This question already has answers here:
Convert from enum ordinal to enum type
(15 answers)
Closed 7 years ago.
I've read a lot about how obtain the corresponding name of an enum from its value using java, but no example seems to work for me! What is wrong?
public class Extensions {
public enum RelationActiveEnum
{
Invited(0),
Active(1),
Suspended(2);
private final int value;
private RelationActiveEnum(final int value) {
this.value = value;
}
}
}
and in another class I use:
int dbValue = supp.ACTIVE;
Extensions.RelationActiveEnum enumValue(dbValue);
String stringName = enumValue.toString(); //Visible
// OR
int dbValuee = supp.ACTIVE;
String stringValue = Enum.GetName(typeof(RelationActiveEnum), dbValue);
I should work, right? but it doesn't!!!! it tells me that dbValue cannote be cast to RelationActiveEnum...
Say we have:
public enum MyEnum {
Test1, Test2, Test3
}
To get the name of a enum variable use name():
MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"
To get the enum from a (string) name, use valueOf():
String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);
If you require integer values to match enum fields, extend the enum class:
public enum MyEnum {
Test1(1), Test2(2), Test3(3);
public final int value;
MyEnum(final int value) {
this.value = value;
}
}
Now you can use:
MyEnum e = MyEnum.Test1;
int value = e.value; // = 1
And lookup the enum using the integer value:
MyEnum getValue(int value) {
for(MyEnum e: MyEnum.values()) {
if(e.value == value) {
return e;
}
}
return null;// not found
}
Since your 'value' also happens to match with ordinals you could just do:
public enum RelationActiveEnum {
Invited,
Active,
Suspended;
private final int value;
private RelationActiveEnum() {
this.value = ordinal();
}
}
And getting a enum from the value:
int value = 1;
RelationActiveEnum enumInstance = RelationActiveEnum.values()[value];
I guess an static method would be a good place to put this:
public enum RelationActiveEnum {
public static RelationActiveEnum fromValue(int value)
throws IllegalArgumentException {
try {
return RelationActiveEnum.values()[value]
} catch(ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Unknown enum value :"+ value);
}
}
}
Obviously this all falls apart if your 'value' isn't the same value as the enum ordinal.
You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.
public static String getNameByCode(int code){
for(RelationActiveEnum e : RelationActiveEnum.values()){
if(code == e.value) return e.name();
}
return null;
}
And call it like this:
RelationActiveEnum.getNameByCode(3);
What you can do is
RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
RelationActiveEnum.ACTIVE.name();
or
RelationActiveEnum ae = RelationActiveEnum.valueOf(
RelationActiveEnum.ACTIVE.name();
or
// not recommended as the ordinal might not match the value
RelationActiveEnum ae = RelationActiveEnum.values()[
RelationActiveEnum.ACTIVE.value];
By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.
public enum RelationActiveEnum {
Invited(0),
Active(1),
Suspended(2);
private final int code;
private RelationActiveEnum(final int code) {
this.code = code;
}
private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
static {
for (RelationActiveEnum rae : RelationActiveEnum.values()) {
BY_CODE_MAP.put(rae.code, rae);
}
}
public static RelationActiveEnum forCode(int code) {
return BY_CODE_MAP.get(code);
}
}
allows you to write
String name = RelationActiveEnum.forCode(RelationActiveEnum.ACTIVE.code).name();
In my case value was not an integer but a String.
getNameByCode method can be added to the enum to get name of a String value-
enum CODE {
SUCCESS("SCS"), DELETE("DEL");
private String status;
/**
* #return the status
*/
public String getStatus() {
return status;
}
/**
* #param status
* the status to set
*/
public void setStatus(String status) {
this.status = status;
}
private CODE(String status) {
this.status = status;
}
public static String getNameByCode(String code) {
for (int i = 0; i < CODE.values().length; i++) {
if (code.equals(CODE.values()[i].status))
return CODE.values()[i].name();
}
return null;
}
If you want something more efficient in runtime condition, you can have a map that contains every possible choice of the enum by their value. But it'll be juste slower at initialisation of the JVM.
import java.util.HashMap;
import java.util.Map;
/**
* Example of enum with a getter that need a value in parameter, and that return the Choice/Instance
* of the enum which has the same value.
* The value of each choice can be random.
*/
public enum MyEnum {
/** a random choice */
Choice1(4),
/** a nother one */
Choice2(2),
/** another one again */
Choice3(9);
/** a map that contains every choices of the enum ordered by their value. */
private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
static {
// populating the map
for (MyEnum myEnum : values()) {
MY_MAP.put(myEnum.getValue(), myEnum);
}
}
/** the value of the choice */
private int value;
/**
* constructor
* #param value the value
*/
private MyEnum(int value) {
this.value = value;
}
/**
* getter of the value
* #return int
*/
public int getValue() {
return value;
}
/**
* Return one of the choice of the enum by its value.
* May return null if there is no choice for this value.
* #param value value
* #return MyEnum
*/
public static MyEnum getByValue(int value) {
return MY_MAP.get(value);
}
/**
* {#inheritDoc}
* #see java.lang.Enum#toString()
*/
public String toString() {
return name() + "=" + value;
}
/**
* Exemple of how to use this class.
* #param args args
*/
public static void main(String[] args) {
MyEnum enum1 = MyEnum.Choice1;
System.out.println("enum1==>" + String.valueOf(enum1));
MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
MyEnum enum3Unknown = MyEnum.getByValue(4);
System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
}
}
This is my take on it:
public enum LoginState {
LOGGED_IN(1), LOGGED_OUT(0), IN_TRANSACTION(-1);
private int code;
LoginState(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static LoginState getLoginStateFromCode(int code){
for(LoginState e : LoginState.values()){
if(code == e.code) return e;
}
return LoginState.LOGGED_OUT; //or null
}
};
And I have used it with System Preferences in Android like so:
LoginState getLoginState(int i) {
return LoginState.getLoginStateFromCode(
prefs().getInt(SPK_IS_LOGIN, LoginState.LOGGED_OUT.getCode())
);
}
public static void setLoginState(LoginState newLoginState) {
editor().putInt(SPK_IS_LOGIN, newLoginState.getCode());
editor().commit();
}
where pref and editor are SharedPreferences and a SharedPreferences.Editor

Categories

Resources