I want to get the child class name which is implemented by an interface. For example
public interface A
public class B implements A
public class C implements A
...
In my code I have declared the interface A and have set the value to one of these classes. So what I have is this:
A a = object.getA();
Now I want to get the current child class name, so B, C or whatever, but I don't want to do it with instanceof because I have many child classes which makes the code unnessesary long. I am basically looking for this but getChild() doesn't exist of course.
a.getChild().getClass().getName()
Thanks in advance!
CodePudding user response:
If I understand the question correctly, it sounds like what you're looking for is:
String name = a.getClass().getName();
// Or
String simpleName = a.getClass().getSimpleName();
If the class of object «a» is an instance of B then getSimpleName() will return "B". It return "C" if «a» is an instance of C and so on.
CodePudding user response:
This will work.
interface A {
}
class B implements A {
}
class C implements A {
}
class Test {
public static void main (String[] args) {
A a = new C();
System.out.println(a.getClass().getName());
}
}