문제

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.

도움이 되었습니까?

해결책

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. :)

다른 팁

Even if you can change the return type, it would not solve the problem. The compiler decides at compile time which implementation of an overloaded method is called. Changing the return type would not change the method that is called. The bytecode would still call the hi(int x) method with a String and probably cause an error.

Your question is too broad. But to get your imagination going, take a look at my old blog about operation overload in Java with some help of ASM framework. Here is a little example from there:

  BigInteger val = Evaluator.evaluate(new Evaluation() {
        public int evaluate(int x, int y) {
          return x - y;
        }
      }, new BigInteger("2"), new BigInteger("3"));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top