Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a URI in Java

Tags:

java

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

import org.eclipse.emf.common.util.URI;

URI cloned = URI.createURI( originalURI.toString() );
like image 769
alesch Avatar asked May 24 '10 10:05

alesch


People also ask

How do you clone URI?

Click Git > Projects from Git and then click Next . Click Clone URI and click Next . In the Source Git Repository window, in the URI field, enter an existing Git repository URL, either local or remote and click Next .

What is a URI in Java?

A URI is a uniform resource identifier while a URL is a uniform resource locator. Hence every URL is a URI, abstractly speaking, but not every URI is a URL.


1 Answers

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.

like image 200
mdma Avatar answered Sep 22 '22 09:09

mdma