Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.example;
import android.support.annotation.IntDef;
import android.util.SparseArray;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import static com.example.Size.ValidSize.SIZE_L;
import static com.example.Size.ValidSize.SIZE_M;
import static com.example.Size.ValidSize.SIZE_S;
public enum Size {
L(SIZE_L), M(SIZE_M), S(SIZE_S);
private volatile static SparseArray<Size> rawValueToEnum;
@ValidSize
private final int rawValue;
Size(@ValidSize int rawValue) {
this.rawValue = rawValue;
}
@ValidSize
public int getRawValue() {
return rawValue;
}
@Retention(RetentionPolicy.SOURCE)
@IntDef({SIZE_L, SIZE_M, SIZE_S})
public @interface ValidSize {
int SIZE_L = 1;
int SIZE_M = 2;
int SIZE_S = 3;
}
public static Size fromRawValue(int rawValue) {
if (rawValueToEnum == null) {
final SparseArray<Size> sizeSparseArray = new SparseArray<>();
final Size[] values = values();
for (Size size : values) {
sizeSparseArray.append(size.getRawValue(), size);
}
// おまけ。値の重複チェックをしておく
if (sizeSparseArray.size() != values.length) {
throw new IllegalStateException("duplicate rawValues in Size enum");
}
rawValueToEnum = sizeSparseArray;
}
final Size size = rawValueToEnum.get(rawValue);
if (size == null) {
throw new IllegalArgumentException("invalid rawValue: " + rawValue);
}
return size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.