为什么Java中没有局部静态变量? [英] Why there is no local static variable in Java?

查看:30
本文介绍了为什么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屋!

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