So, I'm coding an HTTP server in Java using HttpServer. I'm trying to implement my own session state-storing system using cookies and a session ID. The state has to be shared across all the handlers, so I initialized it in the Main file, then passed it into the class like this.
Main.java:
public class Main {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
Map<String, Map<String, String>> sessionData = new HashMap<>();
server.createContext("/test", new Handlers.SessionTestSet(sessionData));
server.setExecutor(null); // creates a default executor
server.start();
}
}
And then, here's the problem. sessionD
(the original object) has to be copied in order to be read by the class itself later, but I don't know if it's a shallow copy or a deep copy, and I need to modify not just sessionData
, but sessionD
as well. How would I modify sessionD
? I also couldn't find anything on Google so sorry if this is a duplicate. And also, clone()
does not work as it is protected.
Handler.java
static class SessionTestSet implements HttpHandler {
private Map<String, Map<String, String>> sessionData;
public SessionTestSet(Map<String, Map<String, String>> sessionD) {
sessionData = sessionD;
}
...
Try this for cloning object -
public class Employee implements Cloneable{
private int empoyeeId;
private String employeeName;
public Employee(int id, String name)
{
this.empoyeeId = id;
this.employeeName = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// Now test cloning
public class Test
{
public static void main(String[] args) throws CloneNotSupportedException
{
Employee original = new Employee(1, "Foo");
//Lets create a clone of original object
Employee cloned = (Employee) original.clone();
//Let verify using employee id, if cloning actually worked
System.out.println(cloned.getEmpoyeeId());
//Must be true and objects must have different memory addresses
System.out.println(original != cloned);
}
}
For Deep cleaning you can add new class inside employee and check. Hope this will help.
I think I get it. Non-primitive objects are automatically shallow cloned if they are copied from the constructor using a copy constructor. Thanks for trying to help anyways!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.