java - 根据固定引用验证参数

标签 java validation parameters

以下方法用于设置FTP连接的传输类型。基本上,我想验证字符输入(请参阅评论)。

这是否太过分了?有更优雅的方法吗?一般而言,您如何进行参数验证?欢迎大家提出意见。

public void setTransferType(Character typeCharacter,
        Character optionalSecondCharacter) throws NumberFormatException,
        IOException {

    // http://www.nsftools.com/tips/RawFTP.htm#TYPE
    // Syntax: TYPE type-character [second-type-character]
    //
    // Sets the type of file to be transferred. type-character can be any
    // of:
    //
    // * A - ASCII text
    // * E - EBCDIC text
    // * I - image (binary data)
    // * L - local format
    //
    // For A and E, the second-type-character specifies how the text should
    // be interpreted. It can be:
    //
    // * N - Non-print (not destined for printing). This is the default if
    // second-type-character is omitted.
    // * T - Telnet format control (<CR>, <FF>, etc.)
    // * C - ASA Carriage Control
    //
    // For L, the second-type-character specifies the number of bits per
    // byte on the local system, and may not be omitted.

    final Set<Character> acceptedTypeCharacters = new HashSet<Character>(Arrays.asList(
            new Character[] {'A','E','I','L'}
    ));

    final Set<Character> acceptedOptionalSecondCharacters = new HashSet<Character>(Arrays.asList(
            new Character[] {'N','T','C'}
    ));

    if( acceptedTypeCharacters.contains(typeCharacter) ) {
        if( new Character('A').equals( typeCharacter ) || new Character('E').equals( typeCharacter ) ){
            if( acceptedOptionalSecondCharacters.contains(optionalSecondCharacter) ) {
                executeCommand("TYPE " + typeCharacter + " " + optionalSecondCharacter );
            }
        } else {
            executeCommand("TYPE " + typeCharacter );
        }
    }
}

最佳答案

通过一次简单的正则表达式检查验证整个字符串:

String.matches("TYPE ([AE] [NTC]|I|L .)")

(请注意,我在 L 之后使用了“.”(任何字符),因为文档没有解释该字符应该是什么。如果它只能是 7 或 8,请使用 [78]。)

您可以更进一步(捕获组、预编译正则表达式、允许任意额外的空格等),但上面的内容基本上做到了。

关于java - 根据固定引用验证参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3030068/

相关文章:

Java 扫描器拆分数组越界

Java Unicode 字符串排序

Spring 3.1 Autowiring 在自定义约束验证器中不起作用

c - C语言中如何判断是否为数字

angular - 如何在 Angular 2 中为异步验证器添加去抖动时间?

bash get 在管道符号之前使用的命令

c++ - 函数原型(prototype)中的参数名称不同

java - Java 中通过 POSIX AIO 或 Windows 重叠 IO 的异步文件 I/O

java - 我想将我从 imageView 裁剪的照片存储到我的私有(private)文件夹中

javascript - 如何使用javascript获取方法参数的值?