Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Enum parameter in method

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?

like image 308
Jean Paul Galea Avatar asked Sep 26 '08 22:09

Jean Paul Galea


People also ask

Can enum pass variables in Java?

So no, you can't have different values of a specific enum constant.

How do you use enum value?

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.

Can enum be private in Java?

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 .


2 Answers

This should do it:

private enum Alignment { LEFT, RIGHT };     String drawCellValue (int maxCellLength, String cellValue, Alignment align){   if (align == Alignment.LEFT)   {     //Process it...   } } 
like image 101
Carra Avatar answered Sep 21 '22 01:09

Carra


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.

like image 23
Joshua DeWald Avatar answered Sep 18 '22 01:09

Joshua DeWald