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.