简体   繁体   中英

Invoking instance method as if it was static through reflection

From simplified perspective, all methods in .Net are actually static. Instance methods invoked by implicitly passing reference to this to first method argument. So, it is possible to call instance method without actually supplying correct instance, making it to behave like static method. Eg it is possible to call string.Equals(string s) as null.Equals(null) either by dynamic emitting call OpCode instead of callvirt or writing corresponding IL code by hand. As I recall, this situation maybe actually encountered if the code was jitted in runtime. And there would be no problem if this is not used within method body.
This thing provides demonstration that methods are actually static in .Net. I'd like to know if there are similar tricks in Java. I've looked through Method.invoke() - it is very thorough in checking that instance methods are not invoked without correct instances, and NullPointerException is guaranteed for null instance. Mostly because all methods in Java are virtual, and for virtual call correct type is required.
So, is there any trick way to call instance method as if it was static in Java (maybe due to some optimization, eg if only one method implementation exists in runtime, virtual call can be changed to non-virtual call)? Or is forbidden due to possible existence of real instance methods (every instance of type has its own method body for that method, not shared between them)?

Certainly not from Java code, no.

If you hand-roll bytecode, then perhaps you could use an invokestatic operation to invoke an instance method, but the result of doing so is not defined in the JVM specifications. Different JVM implementations could -- and probably do -- handle it differently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM