How do I define type constraints for method parameters?… here is a solution to the problem.
How do I define type constraints for method parameters?
I have class A
and interface B
, and one method:
void foo(A x) {}
What I want is to define a constraint on parameter x
, which must implement interface B
.
Although I know it can be done at runtime, for example:
void foo(A x) {
if (!( x instanceof B)) {
throw new IllegalStateException();
}
}
Or define another class and change the method signature, for example:
class C extends A implements B {}
void foo(C x) {}
I don’t
accept this solution because in my case I have many subclasses of A
in the 3rd party jar and I don’t want to modify them.
I
wonder if it can be implemented at the language level, enabling the constraint on the fly when I write the calling code.
Solution
If you must do this, you can use generics such as Bounded Type Parameters . Documentation, Multiboundary section:
public interface A {}
public interface B {}
public static class C implements A, B {}
public static <T extends A & B> void foo(T type) {
}
public static void main(String[] args) {
foo(new A() {}); compile error
foo(new B() {}); compile error
foo(new C() {});
}