Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Java (http://www.velocityreviews.com/forums/f30-java.html)
-   -   Caller info as in Perl (http://www.velocityreviews.com/forums/t148672-caller-info-as-in-perl.html)

soup_or_power@yahoo.com 12-19-2005 05:09 PM

Caller info as in Perl
 
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.


Hendrik Maryns 12-19-2005 05:15 PM

Re: Caller info as in Perl
 
soup_or_power@yahoo.com 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

Robert Klemme 12-19-2005 05:18 PM

Re: Caller info as in Perl
 
soup_or_power@yahoo.com wrote:
> 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.


There are several solutions depending on what you need:
http://groups.google.com/group/comp....d8c5be4024e398


Kind regards

robert


Chris Smith 12-19-2005 05:25 PM

Re: Caller info as in Perl
 
soup_or_power@yahoo.com <soup_or_power@yahoo.com> wrote:
> 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


All times are GMT. The time now is 05:07 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.