Reputation: 1420
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. E.g. 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, e.g. 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)?
Upvotes: 1
Views: 86
Reputation: 181932
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.
Upvotes: 1