Vijay Shanker Dubey
Vijay Shanker Dubey

Reputation: 4418

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 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?

Upvotes: 1

Views: 310

Answers (6)

JSS
JSS

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

biziclop
biziclop

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

G B
G B

Reputation: 3024

I don't think it's possible.

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

Upvotes: 0

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

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

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

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

Oliver Charlesworth
Oliver Charlesworth

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

Related Questions