开发者

way to make a function aware who called it

in java is it possible to make a method aware of who called it (without changing parameters) and then return something else?

public class MyClassA {
   public static final String someStirng = "this is some String"
   public String getSomeString ()
   {
     return someString;
   } 
}

public class MyClassB extends MyClassA {
    public static final String otherstring开发者_如何转开发 = "This is other string"
    public SomeBean getContents()
    {
      SomeBean s = new someBean();
      //if this method gets called from MyCallingClassOther then 
      // i want s.setContents(otherstring)
      s.setContents(getSomeString()); 
      return s;
    }
}

public class MyCallingClass {
    public String callingclassContents ()
    {
      MyClassB myb = new MyClassB();
      return ((SomeBean)myb.getContents()).getFirstName();
    }
}

public class MyCallingClassOther {
    public String callingOtherContents ()
    {
       MyClassB myb = new MyclassB();
       return ((SomeBean)myb.getContents()).getFirstName();
    }
}

so when getContents() method of MyClassB gets called from MyCallingClassOther then I want a different thing returned.

Only code I can change is the body of getContents() (cant change parms). or I can change body of callingOtherContents() in MyCallingClassOther.

This is small piece of a bigger puzzle I am trying to solve ...which obviously was designed poorly. This is kind of a hackway.

Also I'd like to see how it is possible in some other languages?

and If you are wondering why I cant change parameters...thats because I do not want to change anything in callingclassContents() of MyCallingClass


This is small piece of a bigger puzzle I am trying to solve ...which obviously was designed poorly. This is kind of a hackway.

It is possible to do what you want; see @Taylor L's answer. But note that creating an exception in Java doesn't come cheaply.

But my main point is that doing this is almost certainly a bad idea in the long-term. This kind of trickery makes your code harder to understand, and leaves all sorts of little man-traps for people coming after.

IMO, you will be better off changing the method API, and the code that calls it, so that the caller is (in effect) aware of the behavioural differences. In short, fix the bad design, don't make it worse.


This will give you the information regarding the caller. The "1" would change as needed depending upon how many levels above you want to inquire about.

StackTraceElement aParentStack = new Throwable().fillInStackTrace().getStackTrace()[1];
System.out.println(aParentStack.getClassName());
System.out.println(aParentStack.getFileName());
System.out.println(aParentStack.getLineNumber());
System.out.println(aParentStack.getMethodName());
System.out.println((aParentStack.isNativeMethod() ? "Native" : "Java") + " method");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜