Reputation: 15
Problem: I need to add a method to the java.util.prefs.Preferences abstract class, the reasons are as follows:
How can I add a method to an existing Java bytecode?
Upvotes: 1
Views: 852
Reputation: 43972
For java.util.prefs.Preferences
, you are out of luck. This class cannot be instrumented unless you change the classes that are put onto the bootstrap class path. And even if, note that is considered a breach of the JVM's user license agreement to ship an installation with a changed bootstrap class path.
Normally, you can change a class during load time using a Java agent. This way, you could add methods. However, the Preferences
class is used by the JVM internally and it gets loaded before an agent would be loaded. This way, the agent cannot be applied.
Alternatively, the Instrumentation
interface would allow you to change a loaded class at runtime. Using this approach, it is however illegal to add methods which is why this does not work either.
As a third option, you could consider to implement a child-first class loader that shadows the Preferences
class but no class loader other than the bootstrap class loader is allowed to define a class in a java.*
package. Thus, this does not work either.
What you want to do instead:
EnhancedPreferences
that delegate to another Preferences
object it keeps in a field.Preferences
object using static
methods.Upvotes: 2