Generic class to derive from its generic type para

2019-09-13 01:42发布

问题:

Compiles:

public class SerializableObject<T> implements Serializable
{
 public T m_object;
}

Does NOT compile:

public class SerializableObject<T> extends T implements Serializable
{
}

So, I want a generic class to derive from its generic type parameter.
Why?
Let's say I have a Map<K, V> and I simply want to serialize it.
I also don't know ahead which keys I'll have.

How do I do that?

回答1:

So, I want a generic class to derive from its generic type parameter.

You just can't do that, I'm afraid. There are various technical reasons for this, not least of which is type erasure.

You should look for an alternative solution to your issues - this idea is a dead end.



回答2:

Nope, your goal is near a Dynamic type, which java does not support.