【发布时间】:2011-07-26 02:24:33
【问题描述】:
我有一个现有的类,我想在其中添加一个方法。但我希望仅从特定类的特定方法调用该方法。有什么方法可以阻止来自其他类/方法的调用?
例如,我有一个现有的 A 类
public final class A
{
//other stuff available for all classes/methods
//I want to add a method that does its job only if called from a specific method of a class, for example:
public void method()
{
//proceed if called from Class B.anotherMethod() else throw Exception
}
}
一种方法是在method() 中获取StackTrace,然后确认父方法?
我正在寻找的是一种更干净、更可取的解决方案,例如模式或其他东西。
【问题讨论】:
-
您可以尝试在 B 类中使用 method(thisobject) 并在 A 类中使用参数扩展该函数,让它检查 thisobject 是否为 B
-
StackTrace 可以工作,但它是设计时问题的运行时解决方案。