1 package net.pterodactylus.util.envopt;
3 import java.lang.reflect.Field;
4 import java.util.Optional;
5 import java.util.function.Supplier;
8 * Parses values from an {@link Environment} into {@link Option}-annotated fields of an object.
10 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
14 private final Environment environment;
16 public Parser(Environment environment) {
17 this.environment = environment;
20 public <T> T parseEnvironment(Supplier<T> optionsObjectSupplier) {
21 T optionsObject = optionsObjectSupplier.get();
22 Class<?> optionsClass = optionsObject.getClass();
23 for (Field field : optionsClass.getDeclaredFields()) {
24 Option[] options = field.getAnnotationsByType(Option.class);
25 if (options.length == 0) {
28 for (Option option : options) {
29 String variableName = option.name();
30 Optional<String> value = environment.getValue(variableName);
31 if (option.required() && !value.isPresent()) {
32 throw new RequiredOptionIsMissing(option.name());
34 field.setAccessible(true);
36 field.set(optionsObject, value.orElse(option.defaultValue()));
37 } catch (IllegalAccessException iae1) {
45 public static Parser fromSystemEnvironment() {
46 return new Parser(new SystemEnvironment());
49 public static class RequiredOptionIsMissing extends RuntimeException {
51 public RequiredOptionIsMissing(String message) {