如何防止从特定类调用公共方法 [英] How to prevent public methods from being called from specific classes

查看:117
本文介绍了如何防止从特定类调用公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的类,我想添加一个方法。但我想要的方法只从特定的方法从一个特定的类。有没有什么办法,我可以阻止从其他类/方法的调用?



例如,我有一个现有的类A

  public final class A 
{
//其他可用于所有类/方法的东西

//我想添加一个方法,仅当从类的特定方法调用时才执行其工作,例如:

public void method()
{
//如果从类B.anotherMethod()else throw Exception
}
}

这样做是在方法()里面的 StackTrace ,然后确认父方法?



我正在寻找的是一个解决方案,它是一个更干净,更好的解决方案,像一个模式或某事。

解决方案<



如果A类和B类不相关,并且不是同一个包的成员,那么可见性不会解决问题。 (即使是这样,反射可以用来颠覆可见性规则。)



静态代码分析不能解决问题,如果代码可以使用反射调用



传递并检查 B.this 作为 A的额外参数。方法(...)没有帮助,因为一些其他类 C 可以传递 B instance。



这只剩下stacktrace方法...或者放弃并依赖于程序员的好感。 1 不是






理想的解决方案是重新设计和/或编码决策进入这个混乱。






1 - 不要低估程序员的好意。大多数程序员,当他们看到建议不调用某种方法时,很可能会遵循这个建议。


I have an existing class into which I want to add a method. But I want the method to be called only from a specific method from a specific class. Is there any way that I can prevent that call from other classes/methods?

For example, I have an existing class 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
    }
}

One way of doing this is getting the StackTrace inside the method() and then confirming the parent method?

What I am looking for is a solution that is more clean and advisable solution like a pattern or something.

解决方案

To be honest, you have painted yourself into a corner here.

If classes A and B are not related and not members of the same package, then visibility won't solve the problem. (And even if it did, reflection can be used to subvert the visibility rules.)

Static code analysis won't solve the problem if the code can use reflection to call the method.

Passing and checking B.this as an extra parameter to A.method(...) doesn't help because some other class C could pass a B instance.

This leaves only the stacktrace approach ... or giving up and relying on the good sense of the programmer1 not to call methods that they shouldn't.


The ideal solution is to revisit the design and/or coding decisions that got you into this mess.


1 - Do not underestimate the programmer's good sense. Most programmers, when they see advice not to call some method, are likely to follow that advice.

这篇关于如何防止从特定类调用公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆