Reputation: 42050
It looks like a generic
class in java cannot extend a regular non-generic class. What is the reason for that? Is there any workaround?
I was mistaken. As ColinD pointed out my problem was actually with exceptions. Can anybody explain why generic exceptions are not allowed in Java?
Upvotes: 1
Views: 1854
Reputation: 2017
You can! - with certain restrictions. Exceptions are one of those restrictions. You can't make them generic. Erasure removes the exception type information preventing the exception hierarchy from working if you threw generic versions of exceptions. Too bad :(.
Consider this:
import org.apache.commons.collections.set.UnmodifiableSet;
import org.apache.commons.beanutils.BeanMap;
//Can't do this:
//public class MyBeanMap<K, V> extends BeanMap implements Map<K,V>{
//Can do this:
public class MyBeanMap<K, V> extends BeanMap {
//Can't make actual method calls return generic types.
public V get(V arg0) {//Name clash
...
return (V)retval;
}
//Also can't do this:
@override
public V get(V arg0) {//Name clash
return (V)retval;
}
}
I guess you could throw UnsupportedOperation exceptions in overridden methods for the existing interface, and implement your own new generic methods:
public V getGeneric(V){ ... }
but that seems a lot uglier than implementing a facade pattern and just extending the map code, but that is a LOT of intermediate code to create a facade for.
Upvotes: 1
Reputation: 7523
Because exceptions catching require the jvm to know the exact type of exception at runtime (reification) which is not possible in java because all type parameter information is erased by the compiler
Upvotes: 3
Reputation: 83845
public class A {
}
public class B<T> extends A {
}
Works without any problems.
Upvotes: 6
Reputation: 5409
Java seems to do it :
public abstract class AbstractCollection<E>
extends Object
implements Collection<E>
Do you have some code, so we can see the problem?
Upvotes: 4