URI.create() 与新 URI()

URI.create() vs new URI()

可以通过两种方式创建 uri

URI uri = new URI("https://www.google.com/");

或者,

URI uri = URI.create("https://www.google.com/");

我想知道哪种做法更好。我没有注意到任何性能差异并且我已经阅读了文档,但是它有点难以理解。对此有任何见解表示赞赏。

看文档,用法不一样

Creates a URI by parsing the given string.This convenience factory method works as if by invoking the {@link URI(String)} constructor; any {@link URISyntaxException} thrown by the constructor is caught and wrapped in a new {@link IllegalArgumentException} object, which is then thrown.

This method is provided for use in situations where it is known that the given string is a legal URI, for example for URI constants declared within in a program, and so it would be considered a programming error for the string not to parse as such. The constructors, which throw {@link URISyntaxException} directly, should be used situations where a URI is being constructed from user input or from some other source that may be prone to errors.

@param str The string to be parsed into a URI

 * @return The new URI
 *
 * @throws  NullPointerException
 *          If {@code str} is {@code null}
 *
 * @throws  IllegalArgumentException
 *          If the given string violates RFC 2396
 */
public static URI create(String str) {
    try {
        return new URI(str);
    } catch (URISyntaxException x) {
        throw new IllegalArgumentException(x.getMessage(), x);
    }
}

没有区别,因为 URI.create 将调用委托给构造函数。唯一真正的区别是 URI.create(String) 将构造函数抛出的 URISyntaxException(已检查异常)包装到 IllegalArgumentException(未检查异常)中。因此,如果您不想处理已检查的异常,最好只调用 URI.create(String).

这是来自JDK的一段代码:

public static URI create(String str) {
    try {
        return new URI(str);
    } catch (URISyntaxException x) {
        throw new IllegalArgumentException(x.getMessage(), x);
    }
}