Skip to content

Instantly share code, notes, and snippets.

@jesperdj
Created December 13, 2016 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesperdj/0cdd610313d51ff1973f974afdb5a766 to your computer and use it in GitHub Desktop.
Save jesperdj/0cdd610313d51ff1973f974afdb5a766 to your computer and use it in GitHub Desktop.
An enum-like class with a type parameter and a values() method.
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