Instantiate enum class

Internally, enums will be translated to something like this

class Sample extends Enum {
    public static final Sample READ = new Sample("READ", 0);
    public static final Sample WRITE = new Sample("WRITE", 1);

    private Sample(String s, int i)
    {
        super(s, i);
    }

    // More methods, e.g. getter
}

They should not and cannot be initialized.


Here I need to specifying Sample.READ to pass it as parameter. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?

What would "instantiate the enum class" even mean? The point of an enum is that there are a fixed set of values - you can't create more later. If you want to do so, you shouldn't be using an enum.

There are other ways of getting enum values though. For example, you could get the first-declared value:

testEnumSample(Sample.values()[0]);

or perhaps pass in the name and use Sample.valueOf:

testEnumSample("READ");

...

Sample sample = Sample.valueOf(sampleName);

If you explained what you were trying to achieve, it would make it easier to help you.


Enums doesn't support public constructors and hence, cannot be instantiated. Enums are for when you have a fixed set of related constants. Exactly one instance will be created for each enum constant.


Check my answer in another post.

There are 2 ways:

Use Enum.valueOf() static function, then cast it into your enum type.

Enum v = Enum.valueOf(TheEnumClass, valueInString);

Use class.getEnumConstants() function to get the list of the enum constants, and loop this list and get.

Plugins[] plugins = Plugins.class.getEnumConstants();
for (Plugins plugin: plugins) {
    // use plugin.name() to get name and compare
}

Tags:

Java

Enums