Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I modify/update a java.net.URI object?

Tags:

java

uri

updates

Given a java.net.URI object, I need to either:

  • destructively modify one field on that object (e.g. the path component). However there are no setX methods, so it seems these objects are supposed to be immutable.
  • construct a new URI object that is the same as the original except for a given field ("functional update"). However there are no withX methods, so I would have to write my own logic to deal with this.

Do I really have to write my own functions to deal with modification of URI objects?

like image 282
jameshfisher Avatar asked Oct 28 '14 17:10

jameshfisher


1 Answers

Yes you would have create a new object each time since the java.net.URI is immutable. You may use a third-party class like Apache HttpComponents' URIBuilder.

Example from the official tutorial:

URI uri = new URIBuilder()
    .setScheme("http")
    .setHost("www.google.com")
    .setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "")
    .build();    // the build method creates a new URI instance behind the scenes
like image 63
M A Avatar answered Oct 04 '22 10:10

M A