Код: Выделить всё
class Scratch {
interface A1 {
default void print1() { System.out.println("A1"); }
}
interface A2 {
default void print2() { System.out.println("A2"); }
}
interface A3 {
default void print3() { System.out.println("A3"); }
}
static class A1Impl implements A1 {}
static class A2Impl implements A2 {}
static class A3Impl implements A3 {}
static class B implements A1, A2 {}
// Is there any way to make this fail at compile-time if B is not a subtype of T?
static Optional get(Supplier provider, Class clazz) {
if (someCondition()) {
return Optional.of(provider.get());
} else {
// I want to avoid an unchecked cast here to get compile-time safety
return Optional.of((T) new B());
}
}
public static void main(String[] args) {
// Should succeed because B is a subtype of A1 and A2
get(A1Impl::new, A1.class).ifPresent(A1::print1);
get(A2Impl::new, A2.class).ifPresent(A2::print2);
// Will fail at run-time because B is not a subtype of A3
// Is there any way to make this fail at compile-time?
get(A3Impl::new, A3.class).ifPresent(A3::print3);
}
}
Код: Выделить всё
static Optional get(Supplier provider, Class clazz)
Подробнее здесь: https://stackoverflow.com/questions/788 ... ble-from-a