Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace java operators by methods in bytecode using javassist

My Goal

To be able to detect when, at runtime, a comparison is made (or any other operation like, *, - , /, >, < ,...

This should be achieved to edit the bytecode of a class using Javassist or ow2 ASM

What must be achieved

This code

public class Test{

    public void m(){

        if(a>2){
        //blablabla         
        }

    }  

}

Has to become

public class Test{

    public void m(){

        if(someExternalClass.greaterThan(a,2)){
            //blalbla           
    }

    }

}

The greaterThan will return exactly the same result as '>' but will also be used the save the amount of comparisons The external class will then be notified everytime a comparison has been made

Extra note

It has to be done everywhere there is an operation. So not only in if statements.

This means

int a = c+d;

must also become

int a = someExternalClass.add(c,d);

Do you have any suggestions on how I can achieve this with Javassist or other libraries.

I guess it'll have something to do with OpCodes like IFLT, IFGT

like image 789
tgoossens Avatar asked Apr 09 '12 09:04

tgoossens


2 Answers

It might be easier to do this with the source code or at compile time with an annotation processor. For the annotation processor approach you could use Juast or Lombok.

OperatorOverload seems to almost do what you want, it replaces binary expressions with method calls.

like image 183
Sandro Avatar answered Nov 04 '22 01:11

Sandro


This clever hack: http://www.jroller.com/eu/entry/operation_overloading_in_java can give you a hint. The original idea is to give some operator overloading support to Java. You are not doing the exact same thing, but it is somewhat related.

like image 26
Pablo Grisafi Avatar answered Nov 04 '22 02:11

Pablo Grisafi