nz.net.ultraq.preferences:preferences

A simplified and typesafe entry point to the Java Preferences API (java.util.prefs)


License
Apache-2.0

Documentation

Preferences

Build Status Coverage Status Maven Central

A simplified and typesafe entry point to the Java Preferences API (java.util.prefs). I wrote this library out of my wish to use the then-new Java 5 feature of enum's as keys for preference values instead of String constants like most people were doing before Java 5 days.

Installation

Minimum of Java 8 required.

For Maven and Maven-compatible dependency managers

Add a dependency to your project with the following co-ordinates:

  • GroupId: nz.net.ultraq.preferences
  • ArtifactId: preferences
  • Version: (as per the badges above)

Check the project releases for a list of available versions. Each release page also includes a downloadable JAR if you want to manually add it to your project classpath.

Usage

Implement enums that extend from UserPreferencesKey or SystemPreferencesKey to create user/system preferences respectively. Then, use those enum values over an instance of nz.net.ultraq.preferences.Preferences to load/save the relevant preferences. eg:

public enum MyPreferences implements UserPreference {

  WINDOW_WIDTH  (800),
  WINDOW_HEIGHT (600);

  public final Object defaultValue;

  private MyPreferences(Object defaultValue) {
    this.defaultValue = defaultValue;
  }

  @Override
  public Object getDefaultValue() {
    return defaultValue;
  }
}

public class MyClass {

  public static void main(String[] args) {

    Preferences preferences = new Preferences();

    int windowWidth = preferences.get(MyPreferences.WINDOW_WIDTH);
    int windowHeight = preferences.get(MyPreferences.WINDOW_HEIGHT);

    preferences.set(MyPreferences.WINDOW_WIDTH, 1024);
  }
}

API

clear([PreferencesKey preference])

Clears a stored preference, allowing future calls for the preference to revert to its default value. If called without any arguments, this method clears all preferences.

get(Preference preference)

Returns the value of the preference, or the default value if it hasn't been overidden with another value.

set(Preference preference, Object value)

Sets the value of a preference.