I would like to make a new copy and return a java.net.URL. What is the proper way to make a copy of the URL?
Asked
Active
Viewed 807 times
1
-
Have you tried constructing a new one with the same String? – MadConan May 19 '15 at 19:45
-
What do you mean by make a copy? – Aify May 19 '15 at 19:45
-
What are you trying to accomplish? – jgitter May 19 '15 at 19:46
-
Do you want to make a copy of a `java.net.URL` object? Why? The class is [immutable](http://stackoverflow.com/questions/5124012/examples-of-immutable-classes), so it's not necessary to make a copy. – Jesper May 19 '15 at 19:46
-
I may be wrong, but I believe URL is immutable, so there is little point in actually making a copy. – trooper May 19 '15 at 19:47
-
nope guys, not immutable! Ha! ( it should've been ) – ZhongYu May 19 '15 at 19:48
-
@bayou.io Can you show why it's not immutable? – Jesper May 19 '15 at 19:48
-
@Jesper - hmm. it does have setters, but not directly accessible. anyways, it's not exactly "immutable" in the common sense. – ZhongYu May 19 '15 at 19:51
-
I want to return a URL to the user, but don't want them to modify the underlying version. I thought about using clone but am not sure if it will result in a shallow clone. Turns out URL is not immutable (big surprise to me), so decided to ask if anyone has a recommended best practice. To make matters worse, toString calls new URI(url).toString() but not all valid URLs can be represented as valid URIs. To make matters worse, I am not sure if toExternalForm will result in something that can be ingested by another URL. I assume that it can, but there is nothing in the javadoc indicating this. – Frederick F. Kautz IV May 19 '15 at 19:52
-
1How does it allow its state to be changed after its created? Looking at the API I can't identify anything public that does that - once you create a URL, that is it, that object's state isn't going to change ... if you insist on cloning the object anyway, I think you can just feed to result of toString back to the constructor. – trooper May 19 '15 at 19:53
-
Further continuing this, URLStreamHandlers (which extend URL) can call protected void set(). – Frederick F. Kautz IV May 19 '15 at 19:55
-
2@ffk - I don't think you need to worry about that. plenty of APIs return a shared URL. – ZhongYu May 19 '15 at 19:56
-
@bayou.io, thanks for the answer. Quite sad people down voted this so quickly rather than provide a good answer like you did, it is a genuine and pertinent question for me. – Frederick F. Kautz IV May 19 '15 at 20:02
-
@ffk - by default, people think a question is stupid, if it looks simple:) – ZhongYu May 19 '15 at 20:03
1 Answers
4
Common consensus in comments is to not worry about it and just share it. The public API exposed is immutable with exception of a protected set() which is unlikely to be called.

Frederick F. Kautz IV
- 500
- 1
- 4
- 12