private static Runnable instantiate()

in tools/cli/src/main/java/org/apache/batchee/cli/BatchEECLI.java [186:222]


    private static Runnable instantiate(final Class<? extends Runnable> cmd,
                                        final CliConfiguration configuration,
                                        final Map<String, Field> fields,
                                        final boolean hasArgs,
                                        final CommandLine line) throws InstantiationException, IllegalAccessException {
        final Runnable commandInstance = cmd.newInstance();
        if (hasArgs) { // we have few commands we can execute without args even if we have a bunch of config
            for (final Map.Entry<String, Field> option : fields.entrySet()) {
                final String key = option.getKey();
                if (key.isEmpty()) { // arguments, not an option
                    final List<String> list = line.getArgList();
                    if (list != null) {
                        final Field field = option.getValue();
                        final Type expectedType = field.getGenericType();
                        if (ParameterizedType.class.isInstance(expectedType)) {
                            final ParameterizedType pt = ParameterizedType.class.cast(expectedType);
                            if ((pt.getRawType() == List.class || pt.getRawType() == Collection.class)
                                && pt.getActualTypeArguments().length == 1 && pt.getActualTypeArguments()[0] == String.class) {
                                field.set(commandInstance, list);
                            } else {
                                throw new IllegalArgumentException("@Arguments only supports List<String>");
                            }
                        } else {
                            throw new IllegalArgumentException("@Arguments only supports List<String>");
                        }
                    }
                } else {
                    final String value = line.getOptionValue(key);
                    if (value != null) {
                        final Field field = option.getValue();
                        field.set(commandInstance, configuration.coerce(value, field.getGenericType()));
                    }
                }
            }
        }
        return commandInstance;
    }