gpt4 book ai didi

java - 当不这样设置时,发现枚举变量为空

转载 作者:行者123 更新时间:2023-12-01 19:41:03 25 4
gpt4 key购买 nike

每当我尝试从枚举中获取字段时,它总是返回 null。我已经根据枚举构造函数设置了它的值。结果仍然为空。

public enum TeamType {
RED("Red",ChatColor.RED,DyeColor.RED,Point.RED),
BLUE("Blue",ChatColor.BLUE,DyeColor.BLUE,Point.BLUE); //<----Set as Point.RED/BLUE



private String name;
private int crystalHealth = 50;
private Point point;
private int teamPoints;
private ChatColor chatColor;
private DyeColor dye;
private HashSet<ArenaPlayer> playerList = new HashSet<>();
private List<ArenaPlayer> queue = new ArrayList<ArenaPlayer>();
private Location spawn;


public Point getPoint()
{
if(point == null)
System.out.println("WHY? for: " + this.toString()); //<---This always runs

return point;
}

private TeamType(String name,ChatColor color,DyeColor dye,Point point1) {
this.name = name;
this.point = point1; // <--- My assignment
this.dye = dye;
this.chatColor = color;
}

Point 枚举类

public enum Point{
RED(ChatColor.RED + "Red",TeamType.RED),
BLUE(ChatColor.BLUE + "Blue",TeamType.BLUE),
NEUTRAL(ChatColor.WHITE +"None",null);

private String name;
private TeamType teamOwned;
private Point(String name,TeamType team) {
this.name = name;
teamOwned = team;
}

public TeamType getTeamOwned() {
return teamOwned;
}

public String getName() {
return name;
}

@Override
public String toString() {
return name;
}

显然,有些事情发生在我的 Java 知识之外。是否可能是在 TeamType 枚举已初始化时,Point 枚举尚未初始化。这可以解释为什么它是空的。

我需要一些帮助。

最佳答案

嗯,我认为问题的根源在于你有一个循环引用。 TeamType 有一个 Point 引用,反之亦然。

假设TeamType枚举类被初始化,那么枚举常量也被初始化。这些引用 Point,后者依次被初始化。类加载器加载 Point 类,但不会再次初始化 TeamType。此时,您期望为非 null 的属性仍然为 null。

<小时/>

JLS § 12.4定义了这个过程。

关于java - 当不这样设置时,发现枚举变量为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55392680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com