I have a function that I am trying to convert using generics, so far I have:
public static <T extends Enum<T> & SomeInterface> EnumSet<T> convertToES(long val) {
EnumSet<T> es = EnumSet.noneOf(T.class);
for(T t : values()) {
if(t.getSomeProperty() > 0)
es.add(t);
}
return es;
}
Where SomeInterface has a single property getSomeProperty.
T.class isn’t working, and also values() doesn’t seem to work.
Previously I had:
public static EnumSet<SomeType> convertToES(long val) {
EnumSet<SomeType> es = EnumSet.noneOf(SomeType.class);
for (SomeType p : values()) {
if (p.getSomeThing())) > 0) {
es.add(p);
}
}
return es;
}
Is there a way to make this work, or it is not possible?
This is because Java implements generics via erasure so
Tdoesn’t exist at runtime. Generics in Java is just a language tool to help you avoid making too many mistakes that could be caught at compile time.The solution is to require the person calling the method to give you the class itself as a real argument:
As far as
values()is concerned, that method exists on the enum class itself, so if you’ve moved the code out of that class, you’ll need to get the values another way: