I have a method lets say:
private static String drawCellValue( int maxCellLength, String cellValue, String align) { }
and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?
Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.
Any ideas?
So no, you can't have different values of a specific enum constant.
To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Enum FieldsThe enum constructor must be private . You cannot use public or protected constructors for a Java enum . If you do not specify an access modifier the enum constructor it will be implicitly private .
This should do it:
private enum Alignment { LEFT, RIGHT }; String drawCellValue (int maxCellLength, String cellValue, Alignment align){ if (align == Alignment.LEFT) { //Process it... } }
Even cooler with enums you can use switch:
switch (align) { case LEFT: { // do stuff break; } case RIGHT: { // do stuff break; } default: { //added TOP_RIGHT but forgot about it? throw new IllegalArgumentException("Can't yet handle " + align); } }
Enums are cool because the output of the exception will be the name of the enum value, rather than some arbitrary int value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With