6

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

tgoossens
  • 9,676
  • 2
  • 18
  • 23
  • I would replace `if(a>2)` with `someExternalClass.counter++; if(a>2)` – Peter Lawrey Apr 09 '12 at 10:01
  • @PeterLawrey Not entirely. Because in my final code every class will have an identifier. So the actual code would be `someExternalClass.greaterThan(Identifier,a,2)` And also, the code would stop working normally (it is required that the working of the algorithm remains unchanged) – tgoossens Apr 09 '12 at 10:04
  • @PeterLawrey I added an extra example above (see 'Extra Note') – tgoossens Apr 09 '12 at 10:07
  • Either way it will work or not. A method call is more flexible. Have you tried ASM for this? – Peter Lawrey Apr 09 '12 at 10:32
  • @PeterLawrey I did look into that. And normally I think it should be able to the trick. But it was quite complex, so I first searched for something more high level. Do you have any suggestions what parts of ASM I certainly have to study? – tgoossens Apr 09 '12 at 10:34
  • You can override the http://asm.ow2.org/asm33/javadoc/user/org/objectweb/asm/MethodVisitor.html and add additional visits for the extra code you want. – Peter Lawrey Apr 09 '12 at 10:40

2 Answers2

2

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.

Sandro
  • 1,266
  • 2
  • 13
  • 25
2

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.

Pablo Grisafi
  • 5,039
  • 1
  • 19
  • 29