I have following code.
Parent Class:
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..")}
}
Child Class :
class Child extends Parent{
void b(){System.out.println(new Parent().a());}
}
Some Other Class :
class Child1{
void b(){System.out.println(new Parent().a());}
}
Here I am calling Parents a() method from one child class and from other class.
My question is what logic should i put in Parent’s a method’s if block so I can determine which class is calling this method .
I have some code but that is not working.Please help me what is wrong in this code.
if(this.getClass().getClassLoader()
.loadClass(new Throwable().getStackTrace()[0].getClassName())
.newInstance() instanceof Parent)
{
System.out.println("Child class is calling..")}
}
You have these options:
Move
Parentto a different package and makea()protected. Since there are no other classes in the new package, only subclasses will be able to call the method.You can try the stack trace approach but the information you seek isn’t in the first frame – the first frame is where you call
new Throwable(). Try frame 1 instead (that’s the place wherea()was called):If you care about performance, you should cache this result.
That said, I’m wondering what the purpose of this code is. My gut feeling is that you’re fixing a deeper problem by creating a brittle work around which will cause different pains. Maybe you should tell us what you want to achieve (the big picture).