常量对象中声明并赋值的正确写法一:
public class RoleConstant {public static final List<String> PROBLEM_VIEW_ALL_DATA = new ArrayList<String>() {{add("角色1");add("角色2");add("角色3");}};}
常量对象中声明并赋值的正确写法二:
public class RoleConstant {public static final List<String> PROBLEM_VIEW_ALL_DATA = new ArrayList<String>();static{PROBLEM_VIEW_ALL_DATA.add("角色1");PROBLEM_VIEW_ALL_DATA.add("角色2");PROBLEM_VIEW_ALL_DATA.add("角色3");}
}
常量对象中声明并赋值的正确写法三:
public class RoleConstant {public static final List<String> PROBLEM_VIEW_ALL_DATA = Arrays.asList("角色1", "角色2","角色3");
}
service方法中先声明再赋值,不加static也能正常赋值
@Service
public class ProblemEntEvaluateServiceImpl extendsServiceImpl<ProblemEntEvaluateMapper, ProblemEntEvaluate> implementsProblemEntEvaluateService{private static final List<String> ENT_EVALUATE_SATISFACTION_LIST = new ArrayList<>();{ENT_EVALUATE_SATISFACTION_LIST.add("satisfied");ENT_EVALUATE_SATISFACTION_LIST.add("very_satisfied");ENT_EVALUATE_SATISFACTION_LIST.add("basically_satisfied");}
}
问题重现,参考service实现类中的写法在常量对象中使用,在程序运行时发现变量为null
错误写法:
public class RoleConstant {public static final List<String> PROBLEM_VIEW_ALL_DATA = new ArrayList<String>();{PROBLEM_VIEW_ALL_DATA.add("角色1");PROBLEM_VIEW_ALL_DATA.add("角色2");PROBLEM_VIEW_ALL_DATA.add("角色3");}
}
程序运行效果:
出现上述问题,是语法不规范导致的...
常量对象中声明再赋值也是可以正常读取到的,在赋值时少了static{}