獲取首選項的子節點

Preferences 物件總是代表整個 Preferences 樹中的特定節點,有點像這樣:

/userRoot
├── com
│   └── mycompany
│       └── myapp
│           ├── darkApplicationMode=true
│           ├── showExitConfirmation=false
│           └── windowMaximized=true
└── org
    └── myorganization
        └── anotherapp
            ├── defaultFont=Helvetica
            ├── defaultSavePath=/home/matt/Documents
            └── exporting
                ├── defaultFormat=pdf
                └── openInBrowserAfterExport=false

要選擇/com/mycompany/myapp 節點:

  1. 按照慣例,基於類的包:

    package com.mycompany.myapp;
    
    // ...
    
    // Because this class is in the com.mycompany.myapp package, the node
    // /com/mycompany/myapp will be returned.
    Preferences myApp = Preferences.userNodeForPackage(getClass());
    
  2. 按相對路徑:

    Preferences myApp = Preferences.userRoot().node("com/mycompany/myapp");
    

    使用相對路徑(不以/開頭的路徑)將導致路徑相對於其解析的父節點被解析。例如,以下示例將返回路徑/one/two/three/com/mycompany/myapp 的節點:

    Preferences prefix = Preferences.userRoot().node("one/two/three");
    Preferences myAppWithPrefix = prefix.node("com/mycompany/myapp");
    // prefix          is /one/two/three
    // myAppWithPrefix is /one/two/three/com/mycompany/myapp
    
  3. 按絕對路徑:

    Preferences myApp = Preferences.userRoot().node("/com/mycompany/myapp");
    

    在根節點上使用絕對路徑與使用相對路徑沒有區別。不同之處在於,如果在子節點上呼叫,則將相對於根節點解析路徑。

    Preferences prefix = Preferences.userRoot().node("one/two/three");
    Preferences myAppWitoutPrefix = prefix.node("/com/mycompany/myapp");
    // prefix            is /one/two/three
    // myAppWitoutPrefix is /com/mycompany/myapp