开发者

How to clone a URI in Java

开发者 https://www.devze.com 2022-12-31 04:41 出处:网络
Is there a better way to get a copy (clone) of a URI than this horrible hack? import o开发者_如何转开发rg.eclipse.emf.common.util.URI;

Is there a better way to get a copy (clone) of a URI than this horrible hack?

import o开发者_如何转开发rg.eclipse.emf.common.util.URI;

URI cloned = URI.createURI( originalURI.toString() );


URIs are immutable value classes - so you shouldn't really need to make a copy. But if you really need to, then your "hack" (it's really not that bad) is the way to do it.

EDIT: I just noticed you're not using java.net.URI...

From the Eclipse SDK javadocs,

Like String, URI is an immutable class;

That class is also immutable, and the same advice applies. You usually don't need to make a copy, just reuse the URI instance you have. The reason it is safe is that once the object is created, it cannot be changed. Two different clients can use the same URI without fear that it will be modified by the other.

There are methods on URI that update components of the URI (e.g. appendQuery()), but the updates are done on a new instance of URI - the existing URI is unmodified.


Simply write:

Uri newUri = Uri.parse(oldUri.toString());
0

精彩评论

暂无评论...
验证码 换一张
取 消