Java如何清除kidCache?

时间:2015-05-20 21:23:33

标签: java preferences

Java类Preferences有一个名为kidCache的HashMap属性。执行Preferences方法remove(String node)时,节点将从用户的首选项文件中有效删除,但不会从kidCache属性中删除。
因此,当我打印到控制台prefs.nodeExists("account-1")Arrays.toString(prefs.childrenNames())时,它仍然显示为可用。它只会在当前程序完成执行时最终清除。

public class ClassA {
    private Preferences prefs = Preferences.userRoot().node("TestNode");

    public static void main(String[] args) {
        new ClassA();
    }

    public ClassA() {
        prefs = Preferences.userRoot().node("TestNode/account-1");
        prefs.put("username", "testUser1");
        prefs = Preferences.userRoot().node("TestNode");
        prefs.remove("account-1/"); // node removed here
        try {
            System.out.println(prefs.nodeExists("account-1")); // a test for its existance still outputs 'true'
            System.out.println(Arrays.toString(prefs.childrenNames())); // kidCache can be retrieved with this method
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }

    }
}

输出:

Connected to the target VM, address: '127.0.0.1:58572', transport: 'socket'
true
[account-1]

我尝试使用prefs.flush(),但这不起作用。如何在程序执行完毕之前完全清除子节点?

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。虽然我还没弄清楚如何手动清除kidCache,但删除节点的正确方法是设置节点的路径,然后使用removeNode()方法而不是remove(String node)方法一级上升。

public class ClassA {
    private Preferences prefs = Preferences.userRoot().node("TestNode");

    public static void main(String[] args) {
        new ClassA();
    }

    public ClassA() {
        prefs = Preferences.userRoot().node("TestNode/account-1");
        prefs.put("username", "testUser1");
        prefs.removeNode();
        prefs = Preferences.userRoot().node("TestNode");
        try {
            System.out.println(prefs.nodeExists("account-1")); // a test for its existence now outputs 'false'
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }

    }
}

输出

Connected to the target VM, address: '127.0.0.1:58572', transport: 'socket'
false