简体   繁体   中英

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.

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());
  }
}

A simple getClass() on the Object would work.

example :

public class SquaresProblem implements MyInterface {

public static void main(String[] args) {
    MyInterface myi = new SquaresProblem();
    System.out.println(myi.getClass()); // use getClass().getName() to get just the name
    SomeOtherClass.printPassedClassname(myi);
}

@Override
public void someMethod() {
    System.out.println("in SquaresProblem");
}

}

interface MyInterface {
    public void someMethod();
}

class SomeOtherClass {
    public static void printPassedClassname(MyInterface myi) {
        System.out.println("SomeOtherClass : ");
        System.out.println(myi.getClass()); // use getClass().getName() to get just the name
    }
}

O/P :

class SquaresProblem --> class name
SomeOtherClass : 
class SquaresProblem --> class name

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