一个想法是为此创建一个类,例如,maybe ThreadPoolSize
,它封装固定数值或动态值的枚举。您需要为此数据类型创建一个自定义转换器。
然后您可以按如下方式定义选项:
@Option(names = { "-t", "--threads" }, converter = ThreadPoolSizeConverter.class,
description = "[1, n] for fixed thread pool, 'cpus' for number of cpus, 'cached' for cached")
ThreadPoolSize threadPoolSize;
线程池大小和转换器的自定义数据类型可能如下所示:
class ThreadPoolSize {
enum Dynamic { cpus, cached }
int fixed = -1; // if -1, then use the dynamic value
Dynamic dynamic; // if null, then use the fixed value
}
class ThreadPoolSizeConverter implements CommandLine.ITypeConverter<ThreadPoolSize> {
@Override
public ThreadPoolSize convert(String value) throws Exception {
ThreadPoolSize result = new ThreadPoolSize();
try {
result.fixed = Integer.parseInt(value);
if (result.fixed < 1) {
throw new CommandLine.TypeConversionException("Invalid value " +
value + ": must be 1 or more.");
}
} catch (NumberFormatException nan) {
try {
result.dynamic = ThreadPoolSize.Dynamic.valueOf(
value.toLowerCase(Locale.ENGLISH));
} catch (IllegalArgumentException ex) {
throw new CommandLine.TypeConversionException("Invalid value " +
value + ": must be one of " +
Arrays.toString(ThreadPoolSize.Dynamic.values()));
}
}
return result;
}
}