Harry
Harry

Reputation: 4773

How to set enum type to String type

I have one java object which is using enum type

  public class Deal{

public enum PriceType {
        fixed, hour, month, year
    }

     @Element(name = "price-type", required = false)
     private PriceType priceType;

  }

this object is get populated from some API and I am retriving this in database object having string type variable

MyDeal{
    private String priceType;

    public String getPriceType() {
    return priceType;
   }

    public void setPriceType(String priceType) {
    this.priceType = priceType == null ? null : priceType.trim();
   }

}

why can't I set my database object like

 List<Deal>deals = dealResource.getAll(); 
 MyDeal myDeal = new myDeal(); 

 for (Deal deal : deals) {
     myDeal.setPriceType(deal.getPriceType());
 }

Upvotes: 0

Views: 117

Answers (2)

Rahul
Rahul

Reputation: 45060

You can't set a PriceType to a String directly. You need to do something like this

for (Deal deal : deals) {
     myDeal.setPriceType(deal.getPriceType().name()); // name() will get that name of the enum as a String
}

Though the for loop looks seriously flawed. You'll just keep overriding the priceType in myDeal over and over again.

Upvotes: 1

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Add Enumerated to the property

@Enumerated(EnumType.STRING)
@Element(name = "price-type", required = false)
private PriceType priceType;

Upvotes: 1

Related Questions