Using a Javassist to handle a private method of a parent class?

I would like to use Javassist for a Java class tool whose source is out of my control (Java 1.6.0_26-b03, Javassist 3.16.1-GA).

I am relatively new to Javassist, but I think I know the concepts behind it. I read a lot about this, but maybe I missed something. Please see the following really simple code:

File ParentPrivateMethodInstrumentingTest.java:

package test.javassist;

import javassist.*;

public class ParentPrivateMethodInstrumentingTest
{
    public ParentPrivateMethodInstrumentingTest() throws Exception
    {
        ClassPool classPool = ClassPool.getDefault();

        CtClass childCtClass = classPool.get( "test.javassist.Child" );
        CtMethod parentCtMethod = childCtClass.getMethod( "parent", "()V" );

        parentCtMethod.insertBefore( "{ System.err.println( \"-- before parent() --\" ); }" );

        Child child = (Child)childCtClass.toClass().newInstance();
        child.parent();
    }

    public static void main( String[] args ) throws Exception
    {
        new ParentPrivateMethodInstrumentingTest();
    }
}

Parent.java file:

package test.javassist;

public class Parent
{
    private void privateParent()
    {
        System.out.println( "Parent.privateParent()" );
    }

    public void parent()
    {
        System.out.println( "Parent.parent()" );
        privateParent();
    }
}

Child.java file:

package test.javassist;

public class Child extends Parent
{

}

When I run this program, the output is:

Parent.parent()
Parent.privateParent()

So my question is: why is there no "- before parent () -" line that I thought was inserted into the bytecode?

Is it impossible to perform code insertions in the way I tried to use private methods of parent classes?

Many thanks for your help!

+3
1

Framework , , . ,

childCtClass.getSuperclass().toClass();

parentCtMethod.insertBefore

, .

+3

All Articles