开发者

How to make any Java method static at run time?

I am wondering if there is any way to achieve the following.

  1. Find a method using reflection (done)
  2. Change 开发者_Go百科the method access modifier to to public and static. (How?)
  3. execute this method without having any existing instance (How?)

Does reflection has any option to do this?


No, this is completely impossible and makes no sense whatsoever. An instance method has access to (and typically uses) instance variables. What should e.g. a typical set or get method that has been "made static" possibly do?


This doesn't make any sense. A non-static method is non-static for a reason, in that it needs to access member data specific to a particular instance of the class. How would you convert that to static?


Even if you used tools that let you change a class (like BCEL), you still wouldn't have achieved anything, because (all minor caveats aside) the moment you change a method from instance method to static, all code calling it will throw a NoSuchMethodError. The reason being that invoking a static/instance method use two different opcodes.


No. You can't change a class with reflection. You can just inspect it.


I don't think it's possible.

If your method uses a 'this' reference, that would be an undefined behaviour.


As all said this is bad and should not be done.

But again if you have to achieve this and you have already given the reason so I might like to try something different to achieve this.
I might create a singleton class and give a static method (facade) to access the required API method and always make sure that all other classes use this singleton class method to access the API method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜