![](/img/trans.png)
[英]Is it possible to see via which child class was a parent's static method called in Java?
[英]Is there a way to tell which child class called a parent's function in java?
我有两个类扩展相同的 class,例如:
abstract class A {
//functions
}
class B extends A {
//functions
}
class C extends A {
//functions
}
I would like a function in the parent class to change it's behavior depending on which child class is calling the function, for example, a function in class A will execute a different if statement depending on which child class calls the function. 有没有办法让父 class 知道哪个子构造函数正在使用它的 function?
当然,这里是 go:
abstract class A {
// abstract functions
public void myCoolFunction(){
if(this.getClass().equals(B.class)){
System.out.println("B!");
}else{
System.out.println("NOT B!");
}
}
}
class B extends A {
//functions
}
class C extends A {
//functions
}
测试它:
jshell> C c = new C();
c ==> C@6d4b1c02
jshell> c.myCoolFunction();
NOT B!
jshell> B b = new B();
b ==> B@4883b407
jshell> b.myCoolFunction();
B!
顺便说一句,这种技术通常是代码味道或糟糕的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.