简体   繁体   English

为什么在Java中将静态方法中的变量声明为final

[英]why should a variable in a static method be declared as final in java

I am having a static method .In the method when I decalare a variable , it was showing an error in eclipse saying that the variable should be decalared as final. 我有一个静态方法。在该方法中,当我对一个变量进行十进制贴图时,它在eclipse中显示了一个错误,表示该变量应被声明为final。 Can I know the reason for this , y should a variable in a static method be declared as final? 我可以知道原因吗?y是否应将静态方法中的变量声明为final? I am writng an Android application where I should pass as an argument current Context of that application. 我正在编写一个Android应用程序,在该应用程序中应将该应用程序的当前Context作为参数传递。 So, when I pass the current context to the method and trying to copy it in a local variable , I am getting this error saying that the variable should be declared as final. 因此,当我将当前上下文传递给该方法并尝试将其复制到局部变量中时,出现此错误,表明该变量应声明为final。 my method is like this: 我的方法是这样的:

public static void myfunc(Context ctx, int a)  
{                                     
  Context myctx=ctx;                      
}     

error is showing at line where Context myctx=ctx; 错误显示在上下文myctx = ctx的行中; is declared and asking me to declare it as final. 被声明,并要求我将其声明为final。

Not necessarily. 不必要。 You can have a non final variable inside the static function. 您可以在静态函数中包含一个非最终变量。

Classic example: 经典示例:

public static void main(String args[])
{
   int i = 10;
} 

The regular settings of the compiler don't do this. 编译器的常规设置不会执行此操作。 You are not forced to declare it final. 您没有被迫宣布最终。

There are 3rd party tools (like checkstyle and pmd) that can add errors and warnings. 有第三方工具(例如checkstyle和pmd)可以添加错误和警告。 In this case the variable is changed nowhere else in the method, so it can be declared final 在这种情况下,变量不会在方法中的其他任何地方更改,因此可以将其声明为final

And if you have an anonymous class instantiated below the variable, and use the variable there (but you are not showing this to us) - then it must be declared final. 并且,如果您在该变量下实例化了一个匿名类,并在该变量下使用该变量(但您没有向我们展示此变量),则必须将其声明为final。

No, it's not the case. 不,不是这样。 You can make non final variables in static methods. 您可以在静态方法中创建非最终变量。

Its probably being triggered if you declare a variable and then dont modify it afterwards. 如果您声明一个变量,然后再不对其进行修改,则可能会触发它。

The suggestion is that by declaring it final you allow certain JVM optimisations. 建议通过最终声明它,可以允许某些JVM优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM