I want to get the implementation class name from my interface object — is there any way to do this?
I know I can use instanceof
to check the implementation object, but in my application there are nearly 20 to 30 classes implementing the same interface to override one particular method.
I want to figure out which particular method it is going to call.
Open Java Search, enter the interface name, click "Implementors" and you will "find which classes implement a particular interface."
When you call a method on a variable declared as an interface, Java will look up which method to call in the instance's vtable, which is set when you create the instance based on the class. Thus, it actually calls the implementation definde by the class that that object is an instance of at runtime.
You can use ⌘B (macOS), or Ctrl+B (Windows/Linux), to navigate to an implementation. If a method has multiple implementations, IntelliJ IDEA will list them, so you can choose the one that you want.
Just use object.getClass()
- it will return the runtime class used implementing your interface:
public class Test {
public interface MyInterface { }
static class AClass implements MyInterface { }
public static void main(String[] args) {
MyInterface object = new AClass();
System.out.println(object.getClass());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With