Enumeration values ​​as object instances in Java

I have an enum that implements an interface.

Currently, each value is defined in an enum, and an anonymous class is created for each one to override interface methods, for example

interface IReceiver {
    void receive(Object o);
}

      

listing:

enum Receivers implements IReceiver {
    FIRST() {
        @Override
        void receive(Object o) { System.out.println(o); }
    },
    SECOND() {
        @Override
        void receive(Object o) { email(o); }
    };
}

      

Instead, I would like to define each value in a separate class that I create in an enum, but I would rather not write wrapper methods for each, like

enum Receivers implements IReceiver {
    FIRST(new MyFirstObject()),
    SECOND(new MySecondObject());

    IReceiver receiver;

    Receivers(IReceiver receiver) {
        this.receiver = receiver;
    }

    @Override
    void receive(Object o) {
        receiver.receive(o);
    }
}

      

Is there an easy way to do this. Ideally, something like below would be nice:

enum Receivers implements IReceiver {
    FIRST() = new MyFirstObject(),
    SECOND() = new MySecondObject();
}

      

Any suggestions would be appreciated, but I think my second suggestion might be as good as you can achieve in Java.

change the reason for using an enum is to provide a simple and easy way to map individual instances of that interface using the string name

+3


source to share


1 answer


You won't actually need enum

to implement the interface at all if I understand the purpose of your project.

Instead, you can use the injecting constructor IReceiver

as you do in your example.

Then, you either implement the method anonymously or you implement it in your desired concrete implementing class IReceiver

.



Example

interface IReceiver {
    void receive(Object o);
}
class MyReceiver implements IReceiver {
    @Override
    public void receive(Object o) {
        // TODO Auto-generated method stub
    }
}
enum Receivers {
    // anonymous
    FIRST(
        new IReceiver() {
            @Override
            public void receive(Object o) {};
        }
    ), 
    // concrete
    SECOND(new MyReceiver());

    IReceiver receiver;

    Receivers(IReceiver receiver) {
        this.receiver = receiver;
    }

    public IReceiver getReceiver() {
        return receiver;
    }
}

      

+3


source







All Articles