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

6
  • I would replace if(a>2) with someExternalClass.counter++; if(a>2) Commented Apr 9, 2012 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) Commented Apr 9, 2012 at 10:04
  • @PeterLawrey I added an extra example above (see 'Extra Note') Commented Apr 9, 2012 at 10:07
  • Either way it will work or not. A method call is more flexible. Have you tried ASM for this? Commented Apr 9, 2012 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? Commented Apr 9, 2012 at 10:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.