【发布时间】:2010-12-14 12:29:01
【问题描述】:
在java中是否可以让一个方法知道谁调用了它(不改变参数)然后返回别的东西?
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();
}
}
所以当MyClassB 的getContents() 方法从MyCallingClassOther 调用时,我想要返回不同的东西。
我可以更改的唯一代码是 getContents() 的正文(无法更改参数)。或者我可以在MyCallingClassOther 中更改callingOtherContents() 的正文。
这是我正在尝试解决的更大难题的一小部分……显然设计不佳。这有点像hackway。
我还想看看它是如何用其他语言实现的?
如果您想知道为什么我不能更改参数...那是因为我不想更改 callingclassContents() 或 MyCallingClass 中的任何内容
【问题讨论】:
标签: java