Generic class to derive from its generic type para

2019-09-13 01:12发布

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?

2条回答
神经病院院长
2楼-- · 2019-09-13 01:35

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

查看更多
劫难
3楼-- · 2019-09-13 01:51

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.

查看更多
登录 后发表回答