利用反射能创建一个枚举类型的对象吗?

利用反射能创建一个枚举类型的对象吗?

最近有一个需求,需要在源码的基础上增加一个枚举类型,首先,创建一个枚举类(源码提供的)

@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中出现如下异常
在这里插入图片描述
其原因在于底层源码出现无法以反射方式创建枚举对象
在这里插入图片描述总结:不能通过反射方式创建枚举对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值