Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define type constraint on parameter of method?

I have class A and interface B, and a method:

void foo(A x) {}

What I want is to define a constraint on parameter x that it must implement interface B.


Though I know it can be done on runtime, like:

void foo(A x) {
    if (!(x instanceof B)) {
        throw new IllegalStateException();
    }
}

Or define another class and alter method signature, like:

class C extends A implements B {}

void foo(C x) {}

I don't accept this solution since In my case I have many subclasses of A in a 3rd-party jar and I don't want to modify them.


I wonder if it can be achieved on language level, enabling that constraint when I am writing invocation code, on the fly.

like image 729
joooohnli Avatar asked Nov 20 '25 08:11

joooohnli


1 Answers

If you have to do this you can use generics as explained in Bounded Type Parameters docs, "Multiple Bounds" 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() {});
}     
like image 198
Karol Dowbecki Avatar answered Nov 21 '25 20:11

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!