Skip to content

Commit

Permalink
Revert "[remkop#1308] DOC: Add example for Option converter."
Browse files Browse the repository at this point in the history
This reverts commit afec872.
  • Loading branch information
MarkoMackic committed Oct 17, 2021
1 parent 1b1bc9e commit a528008
Showing 1 changed file with 12 additions and 27 deletions.
39 changes: 12 additions & 27 deletions docs/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1133,44 +1133,31 @@ public interface ITypeConverter<K> {
}
----

For example:
Custom type converters can be registered with the `CommandLine.registerConverter(Class<K> cls, ITypeConverter<K> converter)` method. All options and positional parameters with the specified type will be converted by the specified converter.

[source,java]
----
import javax.crypto.Cipher;

class CipherConverter implements ITypeConverter<Cipher> {
public Cipher convert(String value) throws Exception {
return Cipher.getInstance(value);
}
}
----

Custom type converters can be specified for a specific option or positional parameter with the `converter` annotation attribute.
This is described in more detail in the <<Option-specific Type Converters>> section, but here is a quick example:
NOTE: Java 8 lambdas make it easy to register custom converters:

.Java
[source,java,role="primary"]
----
class App {
@Option(names = "-a", converter = CipherConverter.class)
javax.crypto.Cipher cipher;
}
CommandLine cl = new CommandLine(app);
cl.registerConverter(Locale.class, s -> new Locale.Builder().setLanguageTag(s).build());
cl.registerConverter(Cipher.class, s -> Cipher.getInstance(s));
----

.Kotlin
[source,kotlin,role="secondary"]
[source,java,role="secondary"]
----
class App {
@Option(names = ["-a"], converter = [CipherConverter::class])
lateinit var cipher: javax.crypto.Cipher
val cl = CommandLine(app)
cl.registerConverter(Locale::class.java) {
s: String? -> Locale.Builder().setLanguageTag(s).build()
}
cl.registerConverter(Cipher::class.java) {
Cipher.getInstance(it)
}
----


Alternatively, custom type converters can be registered _per type_ in each command with the `CommandLine.registerConverter(Class<K> cls, ITypeConverter<K> converter)` method.
All options and positional parameters with the specified type will be converted by the specified converter.

After registering custom converters, call the `execute(String...)` or `parseArgs(String...)` method on the `CommandLine` instance where the converters are registered. (The static `populateCommand` method cannot be used.) For example:

.Java
Expand Down Expand Up @@ -1198,8 +1185,6 @@ class App {
}
----

NOTE: Java 8 lambdas make it easy to register custom converters:

.Java
[source,kotlin,role="primary"]
----
Expand Down

0 comments on commit a528008

Please sign in to comment.