Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the implementation class name based on the interface object in Java

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.

like image 891
Veera Avatar asked Jul 28 '14 10:07

Veera


People also ask

How do I find the implementation class of an interface in eclipse?

Open Java Search, enter the interface name, click "Implementors" and you will "find which classes implement a particular interface."

How does interface know which implementation to use?

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.

How do I find all implemented classes for an interface in Java Intellij?

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.


1 Answers

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());
  }
}
like image 69
Manuel Avatar answered Oct 03 '22 20:10

Manuel