我怎么知道对象是否是字符串类型的对象?


问题内容

我必须知道Object是String还是任何其他类类型,该怎么办?目前,我像下面那样做,但是它的编码不是很好。

try {
    String myString = (String) object;
    // do stuff here
} catch(Exception e) {
    // it wasn't string, so just continue
}

问题答案:
 object instanceof Type

true如果对象是Type或的子类Type

 object.getClass().equals(Type.class)

true仅当对象是一个Type