0

我想以更短的方式编写此方法。你有什么想法?我没有得到运行的东西......

public static AudioFile getInstance(String pathname) {
    String ending = null;
    int auxvar = pathname.lastIndexOf('.');

    if (auxvar<0) {
        throw new RuntimeException("Unknown suffix for AudioFile: \""+ pathname + "\"");
    }else {
        ending = pathname.substring(auxvar+1);
        ending = ending.toLowerCase();
        if (ending.equalsIgnoreCase("wav")) {
            return new WavFile(pathname);
        }else if (ending.equalsIgnoreCase("mp3") || ending.equalsIgnoreCase("ogg")) {
            return new TaggedFile(pathname);
        }else {
            throw new RuntimeException("Unknown suffix for AudioFile: \" "+ pathname + "\" ");
        }
    }
}
4

2 回答 2

2

好吧,如果你想要那个代码,但更短:

public static AudioFile getInstance(String path) {
    String pathc = path.toLowerCase();
    if (pathc.endsWith(".wav")) return new WavFile(path);
    if (pathc.endsWith("mp3") || pathc.endsWith(".ogg")) return new TaggedFile(path);
    throw new IllegalArgumentException("Unknown suffix for AudioFile: \""+ path + "\"");
}

做同样的事情。

于 2020-05-28T13:33:37.937 回答
0

带有正则表达式的 Monad 风格的解决方案:

final static Pattern audioFilePattern = Pattern.compile(".*\\.(\\w+)");

public static AudioFile getInstance(String path) {
    return Optional.of(path)
        .map(audioFilePattern::matcher).filter(Matcher::matches)
        .map(m -> m.group(1).toLowerCase())
        .filter(s -> Stream.of("wav", "mp3", "ogg").anyMatch(s::equals))
        .map(s -> "wav".equals(s) ? new WavFile(path) : new TaggedFile(path))
        .orElseThrow(() -> new IllegalArgumentException("Unknown suffix for AudioFile: \"" + path + "\""));
}
于 2020-05-28T13:54:00.337 回答