I’ve set the following up as an example.
I have an interface Foo
with various implementations that doThing
. I understand that polymorphism allows different implementations of Foo
to be stored in a collection of Foo
, where each can call their respective doThing
implementation. Can we do something similar based on the bounded generic parameter’s type, like I try with the Consumer<> printer
? It would be very convenient to be able to do this.
import java.util.function.Consumer
public class Tester {
interface Foo {
String doThing();
static String doThing(Class<? extends Foo> clazz) {
return "Class: "+clazz.getSimpleName();
}
static String doThing(Enum<? extends Foo> e) {
return "Enum: "+e.name();
}
static <T extends Foo> String doThing(T e) {
return e.doThing();
}
}
record Bar() implements Foo {
@Override
String doThing() {
return "doing bar";
}
}
enum EnumBar implements Foo {
ENUMFOO;
@Override
String doThing() {
return "doing "+this.name();
}
}
public static void main(String[] args){
System.out.println(Foo.doThing(Bar.class)); // Output: "Class: Bar"
System.out.println(Foo.doThing(new Bar())); // Output: "doing bar"
System.out.println(Foo.doThing(EnumBar.ENUMFOO)); // Output: "Enum: ENUMFOO"
Consumer<? extends Foo> printer = f -> System.out.println(Foo.doThing(f));
// Ideal behaviour
// printer.accept(Bar.class); // Output: "Class: Bar"
// printer.accept(new Bar()); // Output: "doing bar"
// printer.accept(EnumBar.ENUMFOO); // Output: "Enum: ENUMFOO"
}
}
I tried to achieve a similar behaviour where the various static String doThing
logic for each type (Class object, object, enum) is all done in one doThing(Object object)
but the compiler wouldn’t let me safely cast into the various types. Am I forced into using reflection? Or perhaps something with sealed class and the permitted subclasses, but then how does one automatically wrap it with the correct subclass?
RMistri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.