Created
December 13, 2016 16:37
-
-
Save jesperdj/0cdd610313d51ff1973f974afdb5a766 to your computer and use it in GitHub Desktop.
An enum-like class with a type parameter and a values() method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Field; | |
import java.lang.reflect.Modifier; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.function.Supplier; | |
import java.util.stream.Collectors; | |
public final class Example<T> { | |
public static final Example<Integer> INT = new Example<>(Integer.class, () -> 123); | |
public static final Example<String> STR = new Example<>(String.class, () -> "Test"); | |
private final Class<T> type; | |
private final Supplier<T> supplier; | |
private Example(Class<T> type, Supplier<T> supplier) { | |
this.type = type; | |
this.supplier = supplier; | |
} | |
public Class<T> getType() { | |
return type; | |
} | |
public Supplier<T> getSupplier() { | |
return supplier; | |
} | |
public static List<Example<?>> values() { | |
return Arrays.stream(Example.class.getDeclaredFields()) | |
.filter(Example::isConstant) | |
.map(Example::getConstant) | |
.collect(Collectors.toList()); | |
} | |
private static boolean isConstant(Field field) { | |
int modifiers = field.getModifiers(); | |
return Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers); | |
} | |
private static Example<?> getConstant(Field field) { | |
try { | |
return (Example<?>) field.get(null); | |
} catch (IllegalAccessException e) { | |
throw new RuntimeException("Cannot access field: " + field.getName(), e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment