Search code examples
javaproxyjavassistcglibbytecode-manipulation

Can byte-code manipulation change the return type of a Java method at run-time?


I was wondering if it is possible to do something like this with byte-code manipulation:

public class Foo {
    public int getBlah() {
       return 1;
    }
}

public void hi(int x) {
    System.out.println("hi: " + x);
}

public void hi(String x) {
    System.out.println("wow: " + x);
}

Now I want to call:

hi(foo.getBlah());

and invoke the overloading hi method for the String parameter.


Solution

  • Can you handle a flagged value on hi(int x)? If yes you could do something like this:

    public void hi(int x) {
        if (x == Integer.MIN_VALUE) {
            String newParam = getTheParamFromProxySomehow();
            hi(newParam);
            return;
        }    
        System.out.println("hi: " + x);
    }
    

    It is basically:

    • Intercept through a proxy the getBlah() method
    • Save (in a ThreadLocal?) whatever String parameter you want to pass to the overloaded hi method
    • Return the flagged value such as 0, -1 or Integer.MIN_VALUE
    • Do the trick above

    It is a little hacky and it looks best when you don't have a primitive so you can use null as your flagged value. Hopefully someone has a better answer. :)