@SuppressWarnings(QUOT;串行&QUOT) [英] @SuppressWarnings("serial")

查看:148
本文介绍了@SuppressWarnings(QUOT;串行&QUOT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,因为我有点困惑(或者我可能没注意到一些明显的东西)。假设我有一些包含很多类的源代码,这些类包含大量像这样定义的静态字段:

I have a question because I'm getting a little confused (or maybe I'm not noticing something obvious). Let's say that I've got some source code that contains a lot of classes which contain a great number of static fields defined like this one:

public final class ConverterTYPE  {
    private final static HashMap<String, Byte> STRING_MAP = new HashMap<String, Byte>() {
        {
            put("A", new Byte((byte)12));
            put("B", new Byte((byte)13));
        }
    };

}

众所周知,静态字段不会是序列化。

As we all know, static fields are not going to be serialized.

然而,Java(和Eclipse)抱怨可序列化类没有声明类型为long的静态最终serialVersionUID字段。为什么他们不能注意到static不会被序列化?

However, Java (and Eclipse) complains that "The serializable class does not declare a static final serialVersionUID field of type long". Why can't they notice that static is not going to be serialized?

接下来的问题:使用<$ c $这个问题是否正确? c> @SuppressWarnings(serial)摆脱所有这些警告?

And the next question: would it be a right solution to this issue to use @SuppressWarnings("serial") to get rid of all such warnings?

编辑:

我的类都没有实现Serializable接口(或者没有超类)。 Eclipse指向 HashMap< String,Byte> 及其警告。为什么不检测到它是静态字段?

None of my classes implements Serializable interface (or none of their superclasses). And Eclipse is pointing at HashMap<String, Byte> with its warnings. Why doesn't it detect that it's static field?

推荐答案

仅仅因为该字段可能没有被序列化并不代表事物它引用永远不会被序列化!有人/其他东西可以获得对该映射的引用并尝试直接对其进行序列化,或者将其用作可序列化类中的实例成员等。我看到它是私有的,但确保它永远不会在当前类之外访问或设置为实例成员超出了编译器的范围(并且无论如何都无法反射)。

Just because that field may not be serialized doesn't mean the thing it references will never itself be serialized! Someone/thing else could get a reference to that map and try to serialize it directly, or use it as an instance member in a serializable class, etc.I see it is private, but making sure it will never be accessed outside the current class or set to an instance member is beyond the scope of the compiler (and impossible with reflection around anyway).

一种可能的解决方案是简单地避免使用带有初始化程序的匿名子类风格全部并且这样做:

One possible solution is to simply avoid that anonymous subclass w/ initializer style all together and do this:

private final static HashMap<String, Byte> STRING_MAP = new HashMap<String, Byte>();

static {  
  STRING_MAP.put("A", new Byte((byte)12));
  STRING_MAP.put("B", new Byte((byte)13));
}

在大多数情况下,结果大致相同,而且您的代码没有受到影响匿名课程。

The result is close to identical in most cases and your code isn't peppered with anonymous classes.

这篇关于@SuppressWarnings(QUOT;串行&QUOT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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