java中Logger是,在Serializable Java类中使用Logger的正确方法是什么?

I have the following (doctored) class in a system I'm working on and Findbugs is generating a SE_BAD_FIELD warning and I'm trying to understand why it would say that before I fix it in the way that I thought I would. The reason I'm confused is because the description would seem to indicate that I had used no other non-serializable instance fields in the class but bar.model.Foo is also not serializable and used in the exact same way (as far as I can tell) but Findbugs generates no warning for it.

import bar.model.Foo;

import java.io.File;

import java.io.Serializable;

import java.util.List;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

public class Demo implements Serializable {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

private final File file;

private final List originalFoos;

private Integer count;

private int primitive = 0;

public Demo() {

for (Foo foo : originalFoos) {

this.logger.debug(...);

}

}

...

}

My initial blush at a solution is to get a logger reference from the factory right as I use it:

public DispositionFile() {

Logger logger = LoggerFactory.getLogger(this.getClass());

for (Foo foo : originalFoos) {

this.logger.debug(...);

}

}

That doesn't seem particularly efficient, though.

Thoughts?

解决方案

Firstly, don't optimize prematurely. It may be that LoggerFactory.getLogger() is fast enough, and contributes no significant overhead to execution time. If in doubt, profile it.

Secondly, the reason that findbugs isn't complaining about the use of Foo is because the class doesn't have a field of type Foo, it has a field of type List. The generics are erased at compile time, there is no actual reference to Foo in the class, as far as the field definition is concerned. At runtime, the fact that Foo is non-serializable would cause an exception if you tried to serialize an instance of the Demo class, but findbugs can't know this.

My first reaction would be to make the Logger a static field, rather than an instance field. Should work fine in this situation.

public class Demo implements Serializable {

private static final Logger logger = LoggerFactory.getLogger(Demo.class);

// .. other stuff

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值