Java 了解它所指向的继承类
我有一个基类base和一对继承的基类base_1、base_2、base_3。我有一个基于代码的测试,但如何发现它所指向的类:BASE_1、BASE_2或BASE_3 我不清楚你在问什么,但你可以使用Java 了解它所指向的继承类,java,inheritance,Java,Inheritance,我有一个基类base和一对继承的基类base_1、base_2、base_3。我有一个基于代码的测试,但如何发现它所指向的类:BASE_1、BASE_2或BASE_3 我不清楚你在问什么,但你可以使用getClass()方法和instanceof操作符 如果是这样的话 Base b = new Child1(); b.getClass();//will give you child1 要查看特定对象的类名,可以使用: test.getClass().getName(); 但是您通常不应该在意
getClass()
方法和instanceof
操作符
如果是这样的话
Base b = new Child1();
b.getClass();//will give you child1
要查看特定对象的类名,可以使用:
test.getClass().getName();
但是您通常不应该在意,因为任何依赖于您拥有的子类的功能都应该作为这些子类中的重写(“多态”)函数来实现。您可以使用
instanceof
检查特定类型或.getClass()
获取描述特定类的类
对象:
Base test = getSomeBaseObject();
System.out.println("test is a " + test.getClass().getName());
if (test instanceof Base1) {
System.out.println("test is a Base1");
}
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
}