Java,使用多个接口声明变量? [英] Java, declare variable with multiple interfaces?

查看:170
本文介绍了Java,使用多个接口声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否可以声明一个类型为多个接口的字段/变量?例如,我需要声明一个 Map ,它也是 Serializable 。我想确保变量引用可序列化的映射。 Map 界面不会扩展 Serializable ,但大多数 Map 的实现是 Serializable

In Java, is it possible to declare a field/variable whose type is multiple interfaces? For example, I need to declare a Map that is also Serializable. I want to make sure the variable references a serializable map. The Map interface does not extend Serializable, but most of Map's implementations are Serializable.

我很确定答案是否定的。

I'm pretty sure the answer is no.

跟进:我完全了解创建一个扩展 Map 和<$的新界面C $ C>序列化。这不起作用,因为现有的实现(例如 HashMap )没有实现我的新接口。

Follow up: I'm fully aware of creating a new interface that extends both Map and Serializable. This will not work as existing implementations (such as HashMap) do not implement my new interface.

推荐答案

没有必要像那样声明字段/变量。特别是因为它只能测试运行时而不是编译时间。如果传递的Map没有实现Serializable,则创建一个setter并报告错误。

There is no need to declare the field/variable like that. Especially since it can only be tested runtime and not compile time. Create a setter and report an error should the passed Map not implement Serializable.

建议您创建自己的界面的答案当然不是很实用,因为他们会主动禁止发送Maps和Serializable但不是你的特殊界面。

The answers recommending that you create your own interface are of course not very practical as they will actively prohibit sending in things that are Maps and Serializable but not your special interface.

这篇关于Java,使用多个接口声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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