如何限制受保护的方法只能访问子类 [英] how to restrict protected method access to only subclasses

查看:92
本文介绍了如何限制受保护的方法只能访问子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们怎样才能将任何受保护方法的访问权限仅限于任何包中的子类而不是同一包中的类。

How can we restrict access of any protected method to only subclass in any package not to the class in the same package.

如果任何类不是子类并且在同一个包中它也必须像Protected method一样抛出异常。

If any class that is not the subclass and in same package also it must throw exception like "Protected method."

编辑:有没有办法检查调用类名实例然后我们可以使用 instanceof 。

Edit : Is there any way to check calling class name instance and then we can verify using instanceof .

推荐答案

简单:从包中删除所有其他类,只留下你的基类。

Easy: Remove all other classes from the package, leaving only your base class there.

这意味着可以访问您班级的唯一课程来自另一个套餐。

That will mean the only classes that can access your class are from another package.

如果另一个库复制了您的包名,您可以轻松检查调用者的包并断言它与您的包不同:

In the case that another library copies your package name, you could easily check the package of the caller and assert that it isn't the same as yours:

if (getClass().getPackage().equals(MyBaseClass.class.getPackage())
    throw new IllegalAccessError(); // or similar

仅供参考 getClass()为您提供这个的类,这将是子类的类。

FYI getClass() gives you the class of this, which would the subclass's class.

要查找来电者的课程,请使用以下代码:

To find the caller's class, use this code:

Class<?> callerClass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());

这篇关于如何限制受保护的方法只能访问子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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