次のコードがあります。
親クラス:
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());}
}
ここでは、1 つの子クラスと別のクラスから Parents a() メソッドを呼び出しています。
私の質問は、どのクラスがこのメソッドを呼び出しているかを判断できるように、親のメソッドのifブロックにどのロジックを配置する必要があるかです。
私はいくつかのコードを持っていますが、それは機能していません。このコードの何が問題なのか教えてください。
if(this.getClass().getClassLoader()
.loadClass(new Throwable().getStackTrace()[0].getClassName())
.newInstance() instanceof Parent)
{
System.out.println("Child class is calling..")}
}