How to get the type of the class for comparison
I have this object which is an instance of a superclass. I want to know which subclass that object really is, so that I can decide what t开发者_运维问答o do with it. There is this getClass() method but it's apparently not used for comparison issues. How can I get the sub-type of my object?
You may have a design flaw if you're trying to do this but instanceof
.
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
if (s instanceof java.lang.String) {
System.out.println("is a String");
}
}
}
See Beware of instanceof operator.
Class c = (your super class name).getClass();
if(c.getName == "your sub class name") take action
精彩评论