Reputation: 4418
I am wondering if there is any way to achieve the following.
Does reflection has any option to do this?
Upvotes: 1
Views: 310
Reputation: 2183
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.
Upvotes: 0
Reputation: 49734
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.
Upvotes: 1
Reputation: 3024
I don't think it's possible.
If your method uses a 'this' reference, that would be an undefined behaviour.
Upvotes: 0
Reputation: 181280
No. You can't change a class with reflection. You can just inspect it.
Upvotes: 0
Reputation: 346260
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?
Upvotes: 3
Reputation: 272477
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?
Upvotes: 1