因此,我正在使用HttpServer用Java编写HTTP服务器。我正在尝试使用Cookie和会话ID来实现自己的会话状态存储系统。状态必须在所有处理程序之间共享,因此我在Main文件中对其进行了初始化,然后将其传递给此类。
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();
}
}
然后,这就是问题所在。必须复制
sessionD
(原始对象)以便以后由类本身读取,但是我不知道它是浅拷贝还是深拷贝,我不仅需要修改sessionData
,但是sessionD
也是如此。我将如何修改sessionD
?我也无法在Google上找到任何东西,如果这是重复的,对不起。而且,clone()
由于受保护而无法正常工作。Handler.java
static class SessionTestSet implements HttpHandler {
private Map<String, Map<String, String>> sessionData;
public SessionTestSet(Map<String, Map<String, String>> sessionD) {
sessionData = sessionD;
}
...
最佳答案
试试这个克隆对象-
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);
}
}
对于深度清洁,您可以在员工内部添加新班级并进行检查。
希望这会有所帮助。