从泛型类型参数派生的泛型类 [英] Generic class to derive from its generic type parameter

查看:162
本文介绍了从泛型类型参数派生的泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译:

  public class SerializableObject< T>实现Serializable 
{
public T m_object;
}

不会编译:

  public class SerializableObject< T>扩展T implements Serializable 
{
}

所以,我想要一个泛型类从其泛型类型参数派生。

为什么?

比方说,我有一个 Map< K,V> 和I只需要序列化它。

我也不知道我将拥有哪些键。



我该怎么做?

p>

解决方案


所以,我想要一个泛型类派生自它的泛型类型参数。 b $ b

恐怕你不能那样做。这有很多技术上的原因,其中最重要的是擦除类型。



您应该为您的问题寻找替代解决方案 - 这个想法是死路一条。 / p>

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?

解决方案

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.

这篇关于从泛型类型参数派生的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆