static java 初始化_记Java类static成员的一个初始化问题

(代码里面的注释和成员我就省略了)

以下问题虽然我是在enum里遇到的,实际上enum也是个Class,放在Class上照样会出问题。    事情的起因是项目里面有个enum,定义了两个属性code和description,类似如下结构:

public enum LogType {

LOGIN("login", "登陆日志"), ADMIN("admin", "系统管理日志");

private String code = null;

private String description = null;

private LogType(String code, String description) {

this.code = code;

this.description = description;

}

}

但是我在数据库中存储的是code的值,就需要一个方法可以把code转换成对应的枚举,这时就想到创建一个成员,在构造函数里面注册一下,然后就有了以下的改动,却编译报错:

// 增加一个存放code和LogType值对应关系的Map

private static Map instances = new HashMap<>();

// 原计划在构造函数中向map添加这个对象本身,却不能通过编译

private LogType(String code, String description) {

// 这行报错: Cannot refer to the static enum field LogType.instances within an initializer

instances.put(code, this);

this.code = code;

this.description = description;

}     你不是不让我在构造函数里面直接使用enum的static成员吗,那好办,再改一下:

private static Map instances = new HashMap<>();

private void registerCode(String code) {

instances.put(code, this);

}

private LogType(String code, String description) {

registerCode(code);

this.code = code;

this.description = description;

}     这下总能通过编译了吧,我又没在构造函数中直接使用static成员。结果一运行,instances.put(code, this)抛出NullPointerException!!!我不是已经new HashMap<>()了吗。下来查了下资料,得到这样一个说法:

enum在编译后,枚举值和刚才那个静态成员instances会转换为类似如下代码的结构:

public static final LogType LOGIN = new LogType("login", "登陆日志");

public static final LogType ADMIN = new LogType("admin", "系统管理日志");

private static Map instances = new HashMap<>();     对LogType()函数的调用是早于new HashMap<>()这句的执行的。所以NullPointerException就不奇怪了

好吧,我再改,没有保证instances被赋值给new HashMap<>()吗,我加个保证

private static Map instances = null;

private static Map getInstances() {

// 如果instances是null,就给他一个hashMap

if (instances == null) {

instances = new HashMap<>();

}

return instances;

}

// 调用getInstances()而不是直接使用instances,这样就保证instances不为null咯

private void registerCode(String code) {

getInstances().put(code, this);

}

一运行,果然可以了,那继续写find方法

public static LogType find(String code) {

return instances.get(code);

}     使用的时候,又在find里面抛出NullPointerException!!!刚刚构造函数的那里getInstances()明明已经赋值了,我registerCode都放了东西进去了,怎么可能还是null,这不科学。

没法只能开god mode打上断点单步跟一下咯,一看明明getInstances()有调用,registerCode()的时候instances里面的值我都看得清清楚楚...

不过最后又绕回private static Map instances = null 这句把instances改成null了...原因就在这里,最终去掉这个=null,再测试就没有任何问题了

private static Map instances;

总结,static成员的初始化赋值是有可能在对象的构造函数,这时这些成员值为null,这在enum和一些单例模式的写法里面见到。and...没事不要乱写=null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值