Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SomeEnum.values() is defined in an inaccessible class or interface when doing switch over enum

Tags:

java

enums

Let's consider the base class:

package base;

public abstract class Base {
    protected enum BaseEnum {
        FIRST, SECOND, THIRD
    }
}

And its subclass:

package a;

import base.Base;

public class A {
    // The error message appears in case when NestedA is a nested or inner class
    protected /* static */ class InnerA extends Base {
        protected BaseEnum getEnumA() {
            return BaseEnum.FIRST;
        }

        protected int xxx() {
            BaseEnum enumA = getEnumA();
            switch (enumA) {
            // ^^ base.NestedBase.BaseEnum.values() is defined in an inaccessible class or interface
                case FIRST:
                case SECOND:
                    return 1;
                default:
                    return 2;
            }
        }

        protected int xxx2() {
            BaseEnum enumA = getEnumA();
            if (enumA == BaseEnum.FIRST || enumA == BaseEnum.SECOND) {
                return 1;
            } else {
                return 2;
            }
        }

        protected int xxx3() {
            System.out.println(BaseEnum.values());
            return 2;
        }
    }
}

When I am trying to compile it, a compilation error appears on line with switch statement in xxx() saying:

java: base.Base.BaseEnum.values() is defined in an inaccessible class or interface

Briefly the question is what exactly going on here? Why values() is even called here? If it is really called, why is it inaccessible? As you can see, I can properly access BaseEnum and its members from this class (see xxx2()) and even the values() method (which is public method of protected nested enum inside InnerA superclass, see xxx3()). Is access calculated as if this switch would be inside A class? If so, why?

like image 644
Kirill Gagarski Avatar asked Oct 22 '21 20:10

Kirill Gagarski


1 Answers

This has been raised as a bug bugs.openjdk.java.net/browse/JDK-8178701 but has not had feedback from the Java maintainers, as far as I can see. So whether it's considered a valid bug is unclear.

like image 179
tgdavies Avatar answered Oct 20 '22 07:10

tgdavies