开发者

Is it possible to use upper scope object in Java enum?

First class which got the enum:

public class EnumTest {

    private Employee empl;

    public EnumTest(Employee empl) {
        this.empl = empl;
    }

    public enum ALL_STRING {

        FNAME(empl.getFirstName()),
        LNAME(empl.getLastName()),
        POSITION(empl.getPosition());
        String str;

        ALL_STRING(String inStr) {
            str = inStr;
        }

        public String getStr() {
            return str;
        }
    }
}

Employee class:

public class Employee {

    private String firstName;
    private String lastName;
    private String position;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }
}

When I am trying to compile it it gets error that,

/home/shamal/src/Test/src/test/EnumTest.java:21: non-static variable empl cannot be referenced from a static context FNAME (empl.getFirstName()),

/home/shamal/src/Test/src/test/EnumTest.java:22: non-static variable开发者_开发问答 empl cannot be referenced from a static context LNAME (empl.getLastName()),

/home/shamal/src/Test/src/test/EnumTest.java:23: non-static variable empl cannot be referenced from a static context POSITION (empl.getPosition());

3 errors

What is the wrong on the code and what should be the correct way?

Thanks.


Enums are statically (compile time) defined, unique objects, so you can't create their values using dynamic parameters.

The direct problem is that you are trying to instantiate the enum using a nonstatic member variable, which is thus not available at the time of instantiating the class itself - it will only be initialized when a new class object is created. However, all enum values must be fully initialized at the time the enclosing class is initialized.

It is hard to see what you are actually trying to achieve with this code - maybe if you explain it in words, we can offer a better alternative approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜