Navigation

User login

Elsewhere

Reading the Windows Registry from Java without JNI

June 19, 2009
by davidc

Here is a class that allows you to read the Windows Registry without having to install any JNI library. It is implemented purely using introspection and will therefore compile and run on any platform. It would be possible to extend this to also write to the registry, but I didn't need this functionality. I hesistate to call this "pure Java" as it does make native calls, but it does avoid the need for external dependencies to do so.

Operation

I forget who first pointed this out to me, but the java.util.prefs.WindowsPreferences implementation contains handy native methods to read and write any registry key, not just those under Software\Java\Prefs. By evil use of introspection, one can force these to be accessible and use them to read the registry without needing to install a new JNI library.

Figuring out which methods are needed and how to use them is a simple matter of tracing the getSpi() method in WindowsPreferences. From there, one can use the Method.setAccessible() method to bypass JVM security checks and execute them through introspection.

I have not implemented the write methods as I had no need for them, but they should be equally easy to do.

Caveats

Of course, this approach is pure evil*: breaking encapsulation and accessing private members is morally objectionable and liable to break under future versions. For my purposes, the requirement was not mission-critical. It works well enough and there will be no ill-effects if it fails in the future. On non-Windows platforms, or if the WindowsPreferences implementation changes, a BackingStoreException will be thrown.

However, if registry access is critical to your application, try something like JNIRegistry instead.

Comments

May 22, 2014
by nid69ita,
5 years 16 weeks agoComment: 103

Hi, I know it's an old project.
You know if exist some command like RegQueryVal accessible in Java like your system for reading everywhere in registry ?
I need to Enumerate some subkeys in registry.
Thank you, Igor Noro