URI.create()vs new URI() [英] URI.create() vs new URI()
问题描述
uri
可以通过两种方式创建:
URI uri =新URI(https://www.google.com/);
或者,
URI uri = URI.create(https://www.google.com/);
我想知道哪种方式更好。我没有注意到任何性能差异,我已经阅读了文档,但是有点难以理解。对此有任何见解表示赞赏。
阅读文档时,它的用法不同。
通过解析给定的字符串来创建URI。这个便利工厂
方法就好像通过调用{@link
URI(String)}构造函数一样工作;构造函数抛出的任何{@link URISyntaxException}都被捕获并包装在一个新的{@link
IllegalArgumentException}对象中,然后抛出该对象。
此方法用于已知
给定字符串是合法URI 的情况,例如在程序中声明的URI常量
,因此它将是认为字符串不能解析为
编程错误。直接抛出{@link URISyntaxException}的
构造函数应该使用
来自用户输入构造URI或者来自可能容易出错的其他源的
。 / p>
@param str要解析为URI的字符串
* @return新的URI
*
* @throws NullPointerException
*如果{@code str}是{@code null}
*
* @throws IllegalArgumentException
*如果给定的字符串违反了RFC& nbsp; 2396
* /
public static URI create(String str){
try {
return new URI(str);
} catch(URISyntaxException x){
抛出新的IllegalArgumentException(x.getMessage(),x);
}
}
A uri
could be created in two ways:
URI uri = new URI("https://www.google.com/");
Or,
URI uri = URI.create("https://www.google.com/");
I was wondering which is a better practice. I haven't noticed any performance differences and I've read the documentation, however it was a bit difficult to understand. Any insight on this is appreciated.
Reading the docs, it differs in the usage.
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()vs new URI()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!