简体   繁体   中英

have a static method use a non-static member in enum

I have the following code:

private enum DateFormats {
        DDMMYYYY(0, 2, 4),
        MMDDYYYY(2, 0, 4),
        YYYYMMDD(6, 4, 0);

        private final int dayIndex;
        private final int monthIndex;
        private final int yearIndex;

        private DateFormats(int dayIndex, int monthIndex, int yearIndex) {
            this.dayIndex = dayIndex;
            this.monthIndex = monthIndex;
            this.yearIndex = yearIndex;
        }

        //Error happens here...
        private static int getDay(String date){ return Integer.parseInt(date.substring(dayIndex, dayIndex+2)); }
        private static int getMonth(String date){ return Integer.parseInt(date.substring(monthIndex, monthIndex+2)); }
        private static int getYear(String date){ return Integer.parseInt(date.substring(yearIndex, yearIndex+4)); }
    }

The error I'm getting:

non-static variable dayIndex cannot be referenced from a static context
        private static int getDay(String date){ return Integer.parseInt(date.substring(dayIndex, dayIndex+2)); }

I understand the error happens because the function is static and is using a non-static member, which has not been set, to parse an Integer.

I have checked out a lot of posts here on SO about this, but I still can't wrap my head around what the best approach would be.

Any help is much appreciated.

When you create the enum, you have three instances:

DDMMYYYY(0, 2, 4),
MMDDYYYY(2, 0, 4),
YYYYMMDD(6, 4, 0);

Each of these instances has three fields, dayIndex , monthIndex , yearIndex . When you do:

DateFormats.DDMMYYYY.getDay()

You are calling getDay() on the DDMMYYYY instance, and you expect getDay() to use the specific instance variables you setted in the constructor, so it makes no sense for getDay() to be static.

For example:

String date = "12052015";
int day1 = DateFormats.DDMMYYYY.getDay(date);
int day2 = DateFormats.MMDDYYYY.getDay(date);
System.out.println(day1);
System.out.println(day2);

Result:

12
05

Also, I don't see why getDay() , getMonth() , and getYear() should be private, unless you only want to access them from the outer class.

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