sandra.punkt
sandra.punkt

Reputation: 75

Javassist insturmenter

I am new to Java and Javassist. I would like to add a logger before each read-access on one of my primitive variables in certain methods. After some research I came up with this code:

try {
method.instrument(
        new ExprEditor() {
            public void edit(FieldAccess fa) throws CannotCompileException {
                CtField field = null;
                CtClass fieldType = null;
                try {
                    field = fa.getField();
                    fieldType = field.getType();
                } catch (NotFoundException e) {
                    e.printStackTrace();
                }
                if (fa.isReader() && field != null && fieldType.isPrimitive()){
                    System.out.println("Primitive found: " + field.getName());

                    //ToDo: call method before variable access
                    fa.replace("{ $_ = $proceed($$); }");
                }
            }
        }
    );
} catch (CannotCompileException e) {
    e.printStackTrace();
}

Is there a way to call a (logger) method before the variable is accessed, or do I have to solve this in a different way? What's the best way to achieve this by using Javassist?

Hope someone can help me :)

Upvotes: 0

Views: 139

Answers (1)

s s
s s

Reputation: 296

You can use normal logger object to call the logger methods. But make sure to give the jar class path in the manifest file.

Upvotes: 1

Related Questions