gpt4 book ai didi

java - 如何实现两个不同类中需要的枚举?

转载 作者:行者123 更新时间:2023-11-29 04:55:43 28 4
gpt4 key购买 nike

Action :

public class Action {
public static enum Type {
POSITION, MOUSE, KEY, TEXT
}

public final Type type;

public Action() {
this.type = Type.KEY;
}

//properties, getters, setters ...
}

模型:

public class Model {
public static enum Type {
POSITION, MOUSE, KEY, TEXT
}

public final Type type;

public void doSomething() {
Action action = new Action();
switch (action.type) {
case this.Type.POSITION: //cannot convert from Model.Type to Action.Type
//do stuff here
break;
case ...
//more stuff here
break;
default:
//default stuff here
break;
}
}
}

这是我的(简化的)初始方法,但显然行不通。模型需要做一些操作,这取决于 ActionType 有什么,我想确定它而不必跨越两个类之间的边界,这意味着我希望有是比以下更好的解决方案:

Action.Type type = action.type;

最佳答案

您必须将枚举提取到一个单独的源文件中,就像一个类,但类型为“enum”:

public enum Type {
POSITION,
MOUSE,
KEY,
TEXT
}

并通过导入将其访问到您的类中。

您还可以使用 static 关键字将枚举保留在您的一个类中,并通过添加 import 语句在另一个类中访问它

关于java - 如何实现两个不同类中需要的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854380/

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