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
来源:https://stackoverflow.com/questions/24992959/how-can-i-get-the-implementation-class-name-based-on-the-interface-object-in-jav