如果类B和类C扩展了类A,我有一个类型为B或C的对象,我如何确定它是哪种类型的实例?


当前回答

your_instance.getClass().getSimpleName()将给出类型名称,例如:字符串,Integer, Double, Boolean…

其他回答

如果你想在运行时知道,用isinstance()检查是不够的。 使用:

if(someObject.getClass().equals(C.class){
    // do something
}
if (obj instanceof C) {
//your code
}

在这种情况下我们可以使用反射

objectName.getClass().getName();

例子:-

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String name = request.getClass().getName();
}

在这种情况下,您将获得类的名称,该对象传递给HttpServletRequest接口引用变量。

你可以使用:

Object instance = new SomeClass();
instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
instance.getClass(); //will return the SomeClass' Class object

HTH。但我认为大多数时候,将其用于控制流或类似的东西并不是一个好的实践……

your_instance.getClass().getSimpleName()将给出类型名称,例如:字符串,Integer, Double, Boolean…