2

Is it possible to use generics something like that in Java 1.7?

class Test<T> {
    public <Z extends T & Serializable> void method(Z test) {
       ...
    }
}

I would like my method to accept only objects of generic type which implements specific interface.

miszmaniac
  • 825
  • 2
  • 10
  • 21

2 Answers2

1

No, unfortunately it is not possible to use generic extends with a generic type and an interface. In fact, it is not even possible to use generic extends with multiple types. If you could, then you could do something like the following.

class Test<T, B extends Serializable> {

    public <Z extends T & B> void method(Z test) {
        ...
    }
}

This restriction against extending multiple types may be because of type erasure. At runtime the generics are removed and public <Z extends Serializable> simply becomes public Serializable. So what would <Z extends T & Serializable> be replaced with?

Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
1

The most approximated form would be:

class Test<T extends Serializable>
{
    public <Z extends T> void method(Z test)
    {

    }
}
Little Santi
  • 8,563
  • 2
  • 18
  • 46