(java)If enum is static - how is it that another instance is created in my code (using DB40) ?

StackOverflow https://stackoverflow.com/questions/11898122

  •  25-06-2021
  •  | 
  •  

Question

In my code I have the following enum

public ennum BuySell {
  buy('B', true, RoundingMode.DOWN, 1),
  sell('S', false, RoundingMode.UP, -1 buy);


  BuySell(char c, boolean isBuy, RoundingMode roundingMode, int mult) {
     this.aChar = c;
     this.isBuy = isBuy;
     this.isSell = !isBuy;
     this.roundingMode = roundingMode;
     this.mult = mult;
  }

  BuySell(char c, boolean isBuy, RoundingMode roundingMode, int mult, BuySell   oppositeAction) {
     this(c, isBuy, roundingMode, mult);

     this.opposite = oppositeAction;
     oppositeAction.opposite = this;
  }
}

I save objects containing this enum through DB40 and when my system loads it loads those objects. what I see is that the loaded objects contain ButSell with different object id .
Here you go :

enter image description here

you can see that one selling = 9570 and the other is 9576

My quoestion is - how does another instance of this enum is created ? isnt it static ?

How can I avoid it?
Thanks.

Was it helpful?

Solution

You can get multiple instances if

  • You have multiple class loaders.
  • You use Unsafe to create an instance of an Enum class.

Further investigation would be required to determine how to avoid this. e.g. Are you setting the class loader. Is the ClassLoader for the two object different? Does the library use Unsafe.allocateInstance ?

BTW: I would use BUY and SELL rather than buy and sell for enum constants.

OTHER TIPS

You have now two instances of your enum: buy and sell. And they are static. Not your BuySell type.

I would use a factory and in your objects in setBuySell go through factory. I don't know DB40 so it's a wild guess

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top