How to change or replace private method in java class

I have a class whose behavior I would like to change. I need to replace the private method with another implementation. Shared reflection methods allow you to modify a private variable or call private methods. But I have no information on replacing entire methods.

I assume there are best practices for this. This might not be possible with standard Java reflection, but there are probably other tools to recompile bytecode at runtime.

+3


source to share


3 answers


Edit and replace:

One option is to mask the modified copy class (change the code, recompile the code, add the modified classes to the classpath before the patched classes), similar to the approach used here to test how a normally inaccessible method works.

If you don't have the sources to change, you can "rollback" almost any .class file into more or less readable source code using decompilers . Please note that depending on licensing, you may not have permission to do this and / or to redistribute your changes.

Patch via agent:

You can also fix the methods using the -javaagent:<jarpath>[=<options>]

commant-line parameter . An "agent" is a jar that gets the ability to modify loaded classes and change their behavior. More information here .



Mock:

If you have control over where the method is called, you can replace the target instance with a stub version. Libraries like Mockito make this very, very simple:

LinkedList mockedList = mock(LinkedList.class);
// stubbing appears before the actual execution
when(mockedList.get(0)).thenReturn("first");

      

Although Mockito does not natively support mocking private methods (mainly because it is believed that mana is not suitable for viewing other characters), using PowerMock allows you to do this (thanks @talex).

+1


source


Instead of going for advanced methods, there is a simple trick to achieve this.



If you are part of the open source jar, get the source for this class file from grepcode.com. Change the method you want to change and compile. Update your jar / classpath file with this updated class file.

0


source


You cannot replace a method at runtime (at least not without a JVM hack). But you can replace the whole class. There are several ways to do this. For example, you can use a thing called "aspect".

But from my experience I can say that if you have to do this, you have a wrong turn somewhere at the beginning of your journey.

You might be better off taking one step back and looking at the big picture.

0


source







All Articles