Caller info as in Perl

S

soup_or_power

Hi Experts
In Perl it is possible to determine the caller. Is there an equivalent
function in Java? Approximately, this is what I want to do

class A {

function f () {
if (caller is B) do B stuff;
if (caller is C) do C stuff;
}
class B extends A{}
class C extends A{}



Thanks for your help.
 
H

Hendrik Maryns

(e-mail address removed) schreef:
Hi Experts
In Perl it is possible to determine the caller. Is there an equivalent
function in Java? Approximately, this is what I want to do

class A {

function f () {
if (caller is B) do B stuff;
if (caller is C) do C stuff;
}
class B extends A{}
class C extends A{}

You obviously didn´t get the idea of polymorphism.

abstract class A {
function f ();
}

class B extends A{
function f (){
do B stuff;
}
}

class C extends A{
function f (){
do C stuff;
}
}

H.
--
Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org
 
R

Robert Klemme

C

Chris Smith

In Perl it is possible to determine the caller. Is there an equivalent
function in Java? Approximately, this is what I want to do

class A {

function f () {
if (caller is B) do B stuff;
if (caller is C) do C stuff;
}
class B extends A{}
class C extends A{}

First of all, the need to do this is symptomatic of extremely serious
design problems. You should think hard before relying on something like
this.

That said, yes you can do it:

StackTraceElement[] stackTrace = new Throwable().getStackTrace();
assert stackTrace.length >= 2 : "Can't determine calling context";

String callerClassName = stackTrace[1].getClassName();
if (callerClassName.equals("my.package.B")) ...;

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top