简体   繁体   English

如何为枚举创建 getter 和 setter

[英]How to create getters and setters for enum

public enum EventTypeName
{
    MAIN_EVENT(new MainEvent()),
    MAIN_ADJUSTMENT_EVENT(new MainAdjustmentEvent()),
    CUSTOMER_EVENT(new CustomerEvent()),
     EventType eventType;

    private EventTypeName(EventType eventType)
    {
        this.eventType = eventType;
    }

    public EventType getEventType()
    {
        return eventType;
    }
}

I need to make getters and getters and setters for all new events to be declared in enum.我需要为要在枚举中声明的所有新事件制作 getter 和 getter 和 setter。

Apparently you want to instante a new subclass of EventType for each of the various enum objects, when the getEventType method is called.显然,当调用getEventType方法时,您希望为每个枚举对象实例化一个新的EventType子类。

In this situation, do not name your method with get prefix.在这种情况下,不要使用get前缀命名您的方法。 In commonly used JavaBeans conventions, such a prefix indicates an accessory method to retrieve a property of the object.在常用的 JavaBeans 约定中,这样的前缀表示检索 object 的属性的辅助方法。 Given your intentions, a prefix of new or make may be more appropriate.鉴于您的意图,前缀newmake可能更合适。


public enum EventTypeName
{
    MAIN_EVENT , MAIN_ADJUSTMENT_EVENT , CUSTOMER_EVENT ;

    // Assumes MainEvent, MainAdjustmentEvent, and CustomerEvent are all subclasses of EventType. 
    public EventType makeEventType()
    {
        if ( this.equals( MAIN_EVENT ) ) { return new MainEvent() ; }
        if ( this.equals( MAIN_ADJUSTMENT_EVENT ) ) { return new MainAdjustmentEvent() ; }
        if ( this.equals( CUSTOMER_EVENT ) ) { return new CustomerEvent() ; }
    }
}

Usage.用法。

EventType eventType = EventTypeName.MAIN_ADJUSTMENT_EVENT.makeEventType() ;

I get an unsettled feeling from looking at your code, suspecting a poor or flawed design.查看您的代码时,我感到不安,怀疑设计不佳或有缺陷。 Likely from a misunderstanding of enums in Java.可能是由于对 Java 中的枚举的误解。 An enum should not be considered as a collection.不应将枚举视为集合。 You cannot define additional enum objects at runtime;你不能在运行时定义额外的枚举对象; they are defined at compile-time.它们是在编译时定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM