Skip to content

Add support for pluggable ITypeConverterFactory  #1804

@remkop

Description

@remkop

(See discussion in #1707)

There are cases where applications want programmatic control of the type converter used.
The use case mentioned in #1707 is a single type converter for many Enum classes.
Another potential use case is a single type converter for all implementations of an interface.

The proposed interface is as follows:

/**
 * Interface that allows customization of what type converters to use for specific types
 * and options or positional parameters.
 * If a type converter factory is set for a command, then this factory is first queried to produce a type converter.
 * If no type converter factory is set, or the factory returns a null type converter, 
 * then the default picocli logic is used to attempt to find a type converter.
 * @since 4.x
 */
interface ITypeConverterFactory {
    /**
     * Returns a type converter for the specified type for the specified option or positional parameter,
     * or returns {@code null} if the default converter should be used.
     * 
     * @param type the type (or supertype) for which to return a type converter
     * @param argSpec the option or positional parameter for which to return a type converter
     * @return a type converter or {@code null}
     * @since 4.x
     */
    ITypeConverter<? extends T> createTypeConverter(Class<T> type, ArgSpec argSpec);
}

As is the convention with other getters/setters, applications will be able to install a custom type converter factory for the full command hierarchy via a getter and setter in CommandLine:

/** Sets the specified type converter factory for this command and all subcommands. */
CommandLine::setTypeConverterFactory(ITypeConverterFactory) : void

/** Returns the custom type converter factory for this command, or {@code null} if none was set. */
CommandLine::getTypeConverterFactory() : ITypeConverterFactory

As is the convention with other getters/setters, applications will be able to install a custom type converter factory on a per-command basis via a getter and setter in CommandSpec:

/** Sets the specified type converter factory for this command only. */
CommandSpec::typeConverterFactory(ITypeConverterFactory) : void

/** Returns the custom type converter factory for this command, or {@code null} if none was set. */
CommandSpec::typeConverterFactory() : ITypeConverterFactory

There is no default implementation, that is, by default, CommandLine::getTypeConverterFactory() returns null.
If a type converter factory is set, and it returns a non-null type converter, then this converter is used, otherwise the default picocli logic is used to attempt to find a type converter.

@garretwilson Thoughts/feedback?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions