How can I get the implementation class name based on the interface object in Java
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