首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Enum值在构造函数中转换为null?

Enum值在构造函数中转换为null?
EN

Stack Overflow用户
提问于 2020-06-25 04:24:08
回答 1查看 258关注 0票数 0

我有一个要用枚举值实例化的对象。我这样做的方式如下:

代码语言:javascript
复制
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

代码语言:javascript
复制
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");
}

控制台中的输出:

代码语言:javascript
复制
[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

为什么在对象获取过程中将枚举值设置为空?

EN

回答 1

Stack Overflow用户

发布于 2021-10-27 09:55:05

不,Type值没有转换为null,但它只是没有设置。

这就是你在做的事情:

代码语言:javascript
复制
private Type myType; // declare null variable

public MyClass(Type newType) {
   // never set "myType"
}

因此,您必须使用构造函数中给定的值,如下所示:

代码语言:javascript
复制
private Type myType; // declare null variable

public MyClass(Type newType) {
   this.myType = newType;
}

不要忘记对所有变量都这样做。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62567847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档