为什么Java中没有本地静态变量? [英] Why there is no local static variable in Java?
问题描述
在C / C ++中,我们使用静态局部变量来维护方法的状态。但是为什么Java不支持它?
In C/C++ we use static local variables for maintaining a method's state. But why it is not supported in Java?
是的,我可以为此目的使用静态字段。但创建一个只保留一个方法状态的字段是不是有点奇怪?
Yes, I can use an static field for this purpose. But isn't it a bit weird to create a field for maintaining only one method's state?
推荐答案
你找到了唯一的解决方案。
You have found the only solution.
Java从C ++中删除了许多复杂性,这就是其中之一。
Java dropped a number of complexities from C++, and this was one of them.
静态变量作用域一个函数在并发中对你做了讨厌的事情(例如strtok是一个与pthreads一起使用的着名的东西,正是出于这个原因)。
Static variables scoped to a function do nasty things to you in concurrency (e.g. strtok is a famously nasty one to use with pthreads, for exactly this reason).
一般来说,你想要什么是一个有状态的对象。那么有问题的函数应该有一个对象级变量。然后,您可以创建每个维护状态的实例。
In general, what you want is an object with state. The function in question should then have an object-level variable. Then you can create instances that each maintain state.
更容易理解/维护/等。
Much easier to understand/maintain/etc.
如果你真的需要将州维持为单身人士,那么静态字段就是它。
If you truly need to maintain state as a singleton, then static fields are it.
这篇关于为什么Java中没有本地静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!