Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum Types - Self Printing Enums

Tags:

java

enums

I'm trying to write a java function that takes as a parameter an enum type (part of a console based menuing system). This function will then print all of the string representations in the enum.

The enum looks like this:

protected enum main{
    Option1,
    Option2,
    Option3,
    ...
    OptionN,
}

My display function looks like this

public void displayMenu(Enum menu) {
     // Get values from enum type
     Enum menuOps = menu.values();

     // Iterate over values and print
     for(int i =0 ; i < menuOps.length; i++)
            System.out.println( i + menuOps[i].toString() );
}

My problem: Apparently I must not be doing this correctly. The "menu" parameter object doesn't have a values() method in this scenario.

The desired outcome would be the displayMenu() function having an output of:

Option1
Option2
Option3
...
OptionN

Any pointers on where I'm going wrong with this? Any tips on how to implement this functionality?

Much obliged,

Noob

like image 519
certifiedNoob Avatar asked Apr 01 '26 01:04

certifiedNoob


1 Answers

Because your print method is not dependend on a concreate enum instance, it should be based on a concreate enum class, not on an instance of this class

public static <T extends Enum<T>> void printEnum(Class<T> enumClass) {
    for (Enum<T> item : enumClass.getEnumConstants()) {
        System.out.println(item.toString());
    }
}
...
printEnum(MainEnum.class);
like image 58
Ralph Avatar answered Apr 03 '26 16:04

Ralph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!