利用反射能创建一个枚举类型的对象吗?
最近有一个需求,需要在源码的基础上增加一个枚举类型,首先,创建一个枚举类(源码提供的)
@PublicApi
public enum NotificationType {
CURRENT_ASSIGNEE("Current_Assignee", "CurrentAssignee"),
REPORTER("Current_Reporter", "Reporter"),
CURRENT_USER("Remote_User", "CurrentUser"),
PROJECT_LEAD("Project_Lead", "ProjectLead"),
COMPONENT_LEAD("Component_Lead", "ComponentLead"),
SINGLE_USER("Single_User", "User"),
GROUP("Group_Dropdown", "Group"),
PROJECT_ROLE("Project_Role", "ProjectRole"),
SINGLE_EMAIL_ADDRESS("Single_Email_Address", "EmailAddress"),
ALL_WATCHERS("All_Watchers", "AllWatchers"),
USER_CUSTOM_FIELD_VALUE("User_Custom_Field_Value", "UserCustomField"),
GROUP_CUSTOM_FIELD_VALUE("Group_Custom_Field_Value", "GroupCustomField");
private final String dbCode;
private final String restApiName;
private NotificationType(String dbCode, final String restApiName) {
this.dbCode = dbCode;
this.restApiName = restApiName;
}
public String dbCode() {
return dbCode;
}
public String getRestApiName() {
return restApiName;
}
/**
* Returns a NotificationType from the database code that JIRA uses internally.
*
* @param dbCode a magic string stored in the database tables
* @return a notification type
* @throws IllegalArgumentException if you give an invalid string
*/
public static NotificationType from(String dbCode) {
for (NotificationType notificationType : NotificationType.values()) {
if (notificationType.dbCode().equals(dbCode)) {
return notificationType;
}
}
throw new IllegalArgumentException("You have to provide a valid mapped string");
}
}
准备用反射来创建一个枚举类对象
Class clazz = com.atlassian.jira.notification.type.NotificationType.class;
try {
Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class,String.class,String.class);
constructor.setAccessible(true);
Object object = constructor.newInstance("dept",1,"dept","dept");
System.out.println("111111111" + object);
} catch (Exception e) {
e.printStackTrace();
}
原以为可以创建成功,但在Debug中出现如下异常
其原因在于底层源码出现无法以反射方式创建枚举对象
总结:不能通过反射方式创建枚举对象