I defined an enum type that implements an interface as follows:
public enum MyEnum implements MyInterface
{
val1, val2, val3;
private MyEnum() {}
private MyEnum(Parcel in)
{
readFromParcel(in);
}
public void readFromParcel(Parcel in)
{
MyEnum val = MyEnum.values()[in.readInt()];
// ??? How to I assign val to my current enum?
}
}
How do I access the value of the current enum object so I can make the assignment inside of readFromParcel() ? (Please see comment in code)
Inside an instance method, you can refer to the “current
enumobject” as simplythis. It works this way becauseenumconstants are actual objects, i.e. instances of aclass— a very special type ofclass, but aclassnonetheless. (Note that I mentioned that these areenumconstants: it is the convention in Java to use all uppercase letters when naming constants.)Your usage of
values()is also very peculiar (not to mention that it’ll perform horribly since a new array must be constructed at each call). Perhaps you’d want to take a look atEnumMap, which is a special kind ofMapoptimized forenumconstants as keys.If you’re trying to mutate fields contained in these
enumconstants, then you should seriously consider a redesign. You should generally minimize mutability anyway, but having thesestaticsingletons be mutable does not sound like a good design. Instead of having these mutable fields intrinsic within theenumconstants themselves, aMapfrom the constants to these mutable values would be a much better design.See also
enumEnumSetinstead of bit fieldsEnumMapinstead of ordinal indexingVarious questions on Java
enum