I have two enum types (and would like users to be able to add their own).
enum PhoneSensor { A, B };
enum RobotSensor { A, C };
This works fine if I don't use the Enum properties in a method that takes in an enum type.
public <E extends Enum<E>> void registerSensor(E e) {
System.out.print(e);
}
But if I want the template E to be recognized as an enum (for use in a switch here) I get the error "Cannot Switch on a value of type E." (in Eclipse, the 'e' in switch(e) is underlined red)
public <E extends Enum<E>> void registerSensor(EnumSet<E> eSet) {
for (E e : eSet) {
System.out.print("value is ");
// Cannot switch on a value of type E.
// Only convertible int values or enum variables are permitted
switch(e) {
case PhoneSensor.A:
System.out.print(e);
default:
return;
}
}
}
I understand a little bit about erasure, that it wipes out any info about the template at compile time, so that's the problem. But my attempts at passing in the Class clazz or implementing an interface haven't worked. What's a nice solution to this?
The problem is that you can only switch on one known type.
In your case you are trying to switch across multiple possible types which is flawed in itself. (How can users be expect to add to your code here?)
What you need is an interface
interface Sensor {
void sense();
}
enum PhoneSensor implements Sensor {
A, B;
@Override
public void sense() {
System.out.println(this);
}
}
public <E extends Enum<E> & Sensor> void registerSensor(EnumSet<E> eSet) {
for (E e : eSet) {
System.out.print("value is ");
e.sense();
}
}
This way users can add any enum which implements Sensor and they can do whatever they want without having to change your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With