简体   繁体   中英

Refer enum inside an enum

If,

enum Things{
   UNIQUE_THING,
   NON_UNIQUE_THINGS; // Need to specify what n0n-unique things as a separate enum
}

enum NonUniqueThings {
   THING_1,
   THING_2;
}

Is there any way to refer just one enum Things and specify the behavior of NonUniqueThings in it? What I meant, can caller call like -

Things.UNIQUE_THING 

or

Things.NON_UNIQUE_THING.THING_1

Any ideas please?

You can introduce a nullable parameter for Things that will hold some NonUniqueThings value. Of course, you have to then provide a constructor for Things plus a getter for the param, in order to fetch the NonUniqueThings value.

Note that I'm assuming that UNIQUE_THING will not be bound to some NonUniqueThing and that's why it's instantiated with null as a parameter.

enum Things{
   UNIQUE_THING(null),
   NON_UNIQUE_THINGS(NonUniqueThings.THING_1);

   NonUniqueThings param;

   Things(NonUniqueThings param) {
       this.param = param;
   }

   public NonUniqueThing getNonUniqueThing() {
       return param;
   }
}

Then, you can fetch the NonUniqueThings value, bound to each of the Things values, like this:

NonUniqueThings nonUniqueThing = Things.NON_UNIQUE_THING.getNonUniqueThing();

something like this? No realy nice solution it should work.

enum Things {
        UNIQUE_THING,
        NON_UNIQUE_THING(
            NonUniqueThings.A,
            NonUniqueThings.C);

    public final Child[] childs;

    private Things() {
        this.childs = null;
    }

    private Things(Child... childs) {
        this.childs = childs;
    }
}

interface Child {
    //
}

enum NonUniqueThings implements Child {
    A,
    B,
    C;
}

Here you go (if I've understood your need correctly):

public enum Things {
    UNIQUE_THING, NON_UNIQUE_THINGS;

    public enum NonUniqueThings {
        THING_1, THING_2;
    }
}

Could be accessed like:

Things.NonUniqueThings.THING_1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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