java @SafeVarargs为什么私有方法需要是最终的 [英] java @SafeVarargs why do private methods need to be final

查看:122
本文介绍了java @SafeVarargs为什么私有方法需要是最终的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在内部类中有一个私有方法,它是私有的我想使用SafeVarargs注释。但是,我需要有静态或最终方法。为什么私有方法也需要最终?这不是多余的吗?

I have a private method in an inner class which is private I would like to use the SafeVarargs annotation. However, I am required to either have a static or final method. Why does a private method need to be final as well? Isn't this redundant?

推荐答案

这是多余的,你提出了一个很好的观点。

It is redundant, and you bring up an excellent point.

我认为最终或静态要求的真正原因是强制该方法无法被覆盖,因此子类无法篡改数据使@SafeVarargs注释在方法定义上无用的方法。

I think the real reason for the requirement of final or static was to force that the method could not be overridden, and thus a subclass couldn't tamper with data in a way that made the @SafeVarargs annotation useless on the definition of the method.

但是,虽然它是多余的,但它决定并不是很糟糕 - 很多时候,程序员将尽可能使每个方法都私有,然后根据需要慢慢打开课程。如果此方法在私有范围内被标记为final,那么如果必须打开该方法,它仍然可以使用@SafeVarargs注释,只需更改访问级别。如果有意删除了final,那么你会得到编译时错误,但是如果你已经有了,那么删除私有访问权的人(在基于团队的环境中可能不是你自己)也不会混淆为什么删除私有修饰符突然使代码不再编译。

But, although it is redundant, it's not that bad of a decision - many a time, programmers will make every method private as much as possible, and then slowly open the class up as needed. If this method is marked final when it is in private scope, then if the method has to be opened up, it can still have the @SafeVarargs annotation in place with only a change to the access level. If the final is removed intentionally, you'll get the compile time error, but if you had it already, whoever removes the private access (which may not be yourself, in a team-based environment) won't be confused as to why removing the "private" modifier suddenly makes the code no longer compile.

这篇关于java @SafeVarargs为什么私有方法需要是最终的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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