picocli를 사용하도록 기존 애플리케이션을 변환하고 있습니다. 기존 옵션 중 하나는 다음과 같습니다.
-t, --threads [1, n] for fixed thread pool, 'cpus' for number of cpus, 'cached' for cached
이를 통해 옵션은 양의 정수 또는 몇 가지 특수 문자열 중 하나가 될 수 있습니다. 기존 코드는이를 문자열로 취급하고 특수 문자열 중 하나가 아닌 경우 Integer.parseInt
.
물론 picocli로도 똑같은 일을 할 수 있지만, 이것을 처리하는 더 좋은 방법이 있는지 궁금합니다. 예를 들어, 동일한 옵션에 대해 여러 필드를 사용할 수 있으며 전달 된 내용에 따라 적절한 필드를 채울 수 있습니까? 또한 가능한 문자열 옵션에 대해 열거 형을 사용할 수 있습니다.
한 가지 아이디어는 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;
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다