发现它指向的是继承的类

问题描述

| 我有一个基类BASE和几个继承的类BASE_1,BASE_2,BASE_3。我已经在代码BASE测试中进行了测试,但是如何发现它指向的类是:BASE_1,BASE_2或BASE_3?     

解决方法

BASE test = getSomeBase();

// method 1
System.out.println(test.getClass().getName());  // prints the classname

// method 2
if (test instanceof BASE_1) {
   // test is a an instance of BASE_1
}
    ,我不清楚您要问什么,但可以使用
getClass()
方法和
instanceof
运算符。 如果是这样的话
Base b = new Child1();
b.getClass();//will give you child1
    ,要查看特定对象的类名称,可以使用:
test.getClass().getName();
但是您通常不必在意,因为任何依赖于您所拥有的子类的功能都应在这些子类中实现为重写(\“ polymorphic \”)函数。     ,您可以使用
instanceof
检查特定类型,或使用
.getClass()
获取描述特定类的
Class
对象:
Base test = getSomeBaseObject();

System.out.println(\"test is a \" + test.getClass().getName());
if (test instanceof Base1) {
  System.out.println(\"test is a Base1\");
}