首页 > 解决方案 > 枚举值在构造函数中转换为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?

标签: javaenumsbukkit

解决方案


不,该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;
}

不要忘记对所有变量执行此操作。


推荐阅读