开发者

How to get the type of the class for comparison

开发者 https://www.devze.com 2022-12-22 12:19 出处:网络
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 bu

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

0

精彩评论

暂无评论...
验证码 换一张
取 消