Android 将 String 解析为 StringDef
Android parse String into StringDef
我在我的代码中声明了一个 @StringDef
:
@StringDef({NotificationAction.DISPLAYED, NotificationAction.CONTENT_CLICKED,
NotificationAction.ACTION_CLICKED, NotificationAction.DISMISSED})
@Retention(RetentionPolicy.SOURCE)
public @interface NotificationAction {
String DISPLAYED = "Displayed";
String CONTENT_CLICKED = "ContentClicked";
String ACTION_CLICKED = "ActionClicked";
String DISMISSED = "Dismissed";
}
如何将新字符串解析为 NotificationAction 而无需单独与每个字符串进行比较?
在枚举中,我可以直接使用valueOf
函数。我在这里找不到类似的东西。
看来除了实施它你真的无能为力。我所做的是以下内容。
public class Job {
@IntDef(value = {
Status.STOPPED,
Status.STARTED,
Status.NEW
})
@Retention(RetentionPolicy.SOURCE)
@interface JobStatus {
}
public static class Status {
public static final int STOPPED = 0;
public static final int STARTED = 1;
public static final int NEW = 2;
@JobStatus
static int getStatus(int status) {
return status;
}
@JobStatus
static int fromName(String name) {
switch (name) {
case "STOPPED":
return STOPPED;
case "STARTED":
return STARTED;
case "NEW":
return NEW;
default:
return NEW;
}
}
}
}
也许能帮到你。
我在我的代码中声明了一个 @StringDef
:
@StringDef({NotificationAction.DISPLAYED, NotificationAction.CONTENT_CLICKED,
NotificationAction.ACTION_CLICKED, NotificationAction.DISMISSED})
@Retention(RetentionPolicy.SOURCE)
public @interface NotificationAction {
String DISPLAYED = "Displayed";
String CONTENT_CLICKED = "ContentClicked";
String ACTION_CLICKED = "ActionClicked";
String DISMISSED = "Dismissed";
}
如何将新字符串解析为 NotificationAction 而无需单独与每个字符串进行比较?
在枚举中,我可以直接使用valueOf
函数。我在这里找不到类似的东西。
看来除了实施它你真的无能为力。我所做的是以下内容。
public class Job {
@IntDef(value = {
Status.STOPPED,
Status.STARTED,
Status.NEW
})
@Retention(RetentionPolicy.SOURCE)
@interface JobStatus {
}
public static class Status {
public static final int STOPPED = 0;
public static final int STARTED = 1;
public static final int NEW = 2;
@JobStatus
static int getStatus(int status) {
return status;
}
@JobStatus
static int fromName(String name) {
switch (name) {
case "STOPPED":
return STOPPED;
case "STARTED":
return STARTED;
case "NEW":
return NEW;
default:
return NEW;
}
}
}
}
也许能帮到你。