我在JAVA代码中有枚举ERequestTypes
我的枚举包含超过20个元素,每个元素都是我的JAVA代码中的函数名称。现在我想做以下事情,而不是编写 switch(ERequestTypes) case
并在这种情况下以这种方式调用函数:
switch(ERequestTypes a) {
case ERequestTypes.Initialize:
Initialize();
case ERequestTypes.Uninitialize:
Uninitialize();
}
我想用一行来完成。枚举中的所有函数都有相同的参数并返回相同的 int 值。我怎样才能做到这一点?可能会像 C++ 或其他东西一样在枚举中保留函数指针。请帮忙 !
class CRequestValue {
/**
* Constructor.
*
* @param aName - Name of the request.
* @param aCode - Code of the request.
*/
public CRequestValue(String aName, int aCode) {
this.mName = aName;
this.mCode = aCode;
}
private String mName;
private int mCode;
public String GetName() {
return this.mName;
}
public int GetCode() {
return this.mCode;
}
} /* class CRequestValue **/
enum ERequestTypes
{
Initialize(new CRequestValue("Initialize", 0)),
Uninitialize(new CRequestValue("Uninitialize", 1)),
GetDeviceInfoList(new CRequestValue("GetDeviceInfoList", 2)),
GetDeviceInfo(new CRequestValue("GetDeviceInfo", 3));
private CRequestValue mRequestValue;
private ERequestTypes(CRequestValue aRequestValue) {
this.mRequestValue = aRequestValue;
}
public String GetName() {
return this.mRequestValue.GetName();
}
public int GetCode() {
return this.mRequestValue.GetCode();
}
} /* enum ERequestTypes **/
最佳答案
我不确定你的目标是什么,但你可以使用多态性而不是 switch block ,例如:
interface Invokable {
int init(Object arg);
int uninit(Object arg);
}
enum Request {
INIT() {
@Override
public int invoke(Invokable invokable, Object arg) {
return invokable.init(arg);
}
},
UNINIT() {
@Override
public int invoke(Invokable invokable, Object arg) {
return invokable.uninit(arg);
}
},
;
public abstract int invoke(Invokable invokable, Object arg);
}
Invokable i = ....;
Object arg = ....;
Request r = Request.INIT;
r.invoke(i, arg); // should invoke Invokable.init(arg);
r = Request.UNINIT;
r.invoke(i, arg); // should invoke Invokable.uninit(arg);
关于java - 从枚举调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11263913/