getting element type of EnumSet at runtime

I need to get the element type of an empty EnumSet at runtime. Is this possible? I see that EnumSet has a private field called elementType which stores the type of Enum in the set. Unfortunately, this isn't exposed, which is an odd decision on Sun's part IMHO.

Any other trick to get the element type? The generics information isn't available at runtime, only at compile-time...

Thanks!

Dustin

[421 byte] By [Dustin_Fraziera] at [2007-9-23]
# 1
Only thing I can think of is to use EnumSet.complementOf(EnumSet) to get the empty set's complement and then look at the type of an arbitrary element.
AlexHudsa at 2007-7-13 > top of java,Core,Core APIs...
# 2

Even complementOf does not work because it does not compile at all.

import java.util.*;

enum Colors {

RED, BLUE, WHITE

};

enum Numbers {

ONE, TWO, THREE

}

class TestEnumSet {

public static void printEnumType (EnumSet <?> en) {

System.out.println (en);

System.out.println (EnumSet.complementOf (en)); // does not compile

}

public static void main(String[] args) {

printEnumType (EnumSet.noneOf (Colors.class));

printEnumType (EnumSet.noneOf (Numbers.class));

}

}

Error:

TestEnum.java:13: <E>complementOf(java.util.EnumSet<E>) in java.util.EnumSet can

not be applied to (java.util.EnumSet<capture of ?>)

System.out.println (EnumSet.complementOf (en)); // does not compile

edsonwa at 2007-7-13 > top of java,Core,Core APIs...
# 3
You can try posting a RFE at Sun's Bug Database. Ask for a method called "getElementType" in the EnumSet class. It's a very slight modification that could be safely implemented in Mustang.
edsonwa at 2007-7-13 > top of java,Core,Core APIs...
# 4

> Even complementOf does not work because it does not compile at all.

This might be a javac compiler bug. The same code compiles and runs fine in Eclipse 3.1.

I haven't thought about this carefully, but I was under the impression that capture conversion could deal with this case. Will take a closer look.

AlexHudsa at 2007-7-13 > top of java,Core,Core APIs...