Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumeration Values As Instances of Objects In Java

I have an enumeration that implements an interface.

Currently, each value is defined in the enumeration and an anonymous class is created for each to override the interface methods, eg

interface IReceiver {
    void receive(Object o);
}

with enum:

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, which I instantiate in the enum, but I would prefer not to have to write wrapper methods for each, eg

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 any easy way to do this. Ideally something like the 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 may be as good as you can achieve in Java.

edit the reason for using an enum, is to provide a clear and easy way to map to single instances of this interface, using a string name

like image 716
Joshua Bambrick Avatar asked Dec 14 '25 06:12

Joshua Bambrick


1 Answers

You may actually not need for your enum to implement the interface at all, if I understand the goal of your design.

Instead, you could use a constructor injecting an IReceiver the way you do it already in your example.

Then, you either implement the method anonymously, or you have it implemented in your desired concrete class implementing 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;
    }
}
like image 200
Mena Avatar answered Dec 15 '25 18:12

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!