我有以下代码。
家长班:
class Parent{
void a()
{
if(// some logic to check whether child class is calling this method or some other class//)
System.out.println("Child class is calling..")}
}
儿童班:
class Child extends Parent{
void b(){System.out.println(new Parent().a());}
}
其他一些类:
class Child1{
void b(){System.out.println(new Parent().a());}
}
在这里,我从一个子类和另一个类调用父母 a() 方法。
我的问题是我应该在 Parent 的方法的 if 块中放入什么逻辑,以便我可以确定哪个类正在调用这个方法。
我有一些代码,但它不起作用。请帮我看看这段代码有什么问题。
if(this.getClass().getClassLoader()
.loadClass(new Throwable().getStackTrace()[0].getClassName())
.newInstance() instanceof Parent)
{
System.out.println("Child class is calling..")}
}