Skip to content

MyTalkzHub

Menu
  • Home
  • Coding Articles
  • Marketing
  • Celebrity
  • How To
Menu
Create Generic method constraining T to an Enum

Create Generic method constraining T to an Enum

Posted on December 15, 2022

Here is an example of a generic method that constrains the type parameter T to an Enum:

public static <T extends Enum<T>> void printValues(Class<T> enumType) {
    for (T t : enumType.getEnumConstants()) {
        System.out.println(t.name() + ": " + t.ordinal());
    }
}

To use this method, you would pass in the Class object of the Enum type you want to print the values for. For example:

enum DayOfWeek {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

...

printValues(DayOfWeek.class);

This would print the names and ordinal values of the constants in the DayOfWeek Enum, like this:

SUNDAY: 0
MONDAY: 1
TUESDAY: 2
WEDNESDAY: 3
THURSDAY: 4
FRIDAY: 5
SATURDAY: 6

Note that the Enum type parameter T is specified in angle brackets (<T>) after the method name and before the return type. The extends Enum<T> part is the type constraint, which specifies that the type parameter T must be or extend (i.e., be a subtype of) the Enum class. This ensures that only Enum types can be used as type arguments when invoking the method.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to Review Your Sales Funnel
  • How to Sell a Sales Funnel
  • How to Test a Sales Funnel
  • How to Track Your Sales Funnel
  • How to Use the Sales Funnel

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022

Categories

  • Celebrity
  • Coding Articles
  • How To
  • Marketing
©2023 MyTalkzHub | Design: Newspaperly WordPress Theme