java - 枚举值在构造函数中转换为null?
问题描述
我有一个我想用枚举值实例化的对象。我通过以下方式执行此操作:
Nation gaul = new Nation("gaul", Color.GREEN, 10, ChatColor.DARK_GREEN, Material.GREEN_WOOL, org.bukkit.ChatColor.DARK_GREEN, Statics.NORTH, Type.SWAMP);
这种情况下的枚举值为Type.SWAMP
然而,在对象实例化期间,该Type
值以某种方式被转换为null
public Nation(String nationName, Color color, int id, ChatColor chatColor, Material woolMaterial, org.bukkit.ChatColor bukkitChatColor, String ramSwingDirection, Type biomeType) {
//stuff
this.biomeType = biomeType;
System.out.println(biomeType + " is the value of the passed enumValue");
}
控制台输出:
[00:12:53] [Server thread/INFO]: null is the value of the biomeType
[00:12:53] [Server thread/ERROR]: Error occurred while enabling nationsatwar v1.1 (Is it up to date?)
java.lang.IllegalArgumentException: The validated object is null
at org.apache.commons.lang.Validate.notNull(Validate.java:192) ~[server.jar:git-Spigot-a99063f-
c9d7c16]
at org.apache.commons.lang.Validate.notNull(Validate.java:178) ~[server.jar:git-Spigot-a99063f-
c9d7c16]
at org.bukkit.craftbukkit.v1_15_R1.entity.CraftVillager.setVillagerType(CraftVillager.java:57) ~
[server.jar:git-Spigot-a99063f-c9d7c16]
at net.mcnations.nationsatwar.general.packets.npcs.Architect.spawnEntity(Architect.java:108) ~
[?:?]
顶行声明这个值在简单地传递到对象的构造函数后为空......
这是类型的 javadoc:https ://hub.spigotmc.org/javadocs/spigot/org/bukkit/entity/Villager.Type.html
为什么在对象实例化期间将枚举值设置为 null?
解决方案
不,该Type
值不会转换为 null,但它只是没有设置。
这就是你正在做的事情:
private Type myType; // declare null variable
public MyClass(Type newType) {
// never set "myType"
}
因此,您必须使用构造函数中的给定值,如下所示:
private Type myType; // declare null variable
public MyClass(Type newType) {
this.myType = newType;
}
不要忘记对所有变量执行此操作。
推荐阅读
- kotlin - MutableStateFlow 类在哪里?
- reactjs - 在 redux 中进行循环调度是否正确?
- java - 如何在 Jmeter 中传递仅适用于工作日的日期(yyyy-MM-dd)
- python - 无法使按钮在 Tkinter 中正常工作
- wordpress - 添加订单时出现 Wocomerce API 内部服务器错误
- python - 通过比较行来过滤 pandas pandas 数据框
- javascript - 当 Com1 和 Com2 是兄弟姐妹时,如果触发功能,类型“parentCom”上不存在属性“childCom1”
- r - 在 gsub r 中使用正则表达式模式
- docker - 如何在 terraform 0.14 中选择正确的 docker 提供程序
- javascript - 如何在 React 中显示 json 数据的特定键