java 将类的静态变量重新初始化为其原始值java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7979331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
re-initialize the static variables of a class to their original values java
提问by Peter Berg
I have a class that has a fair amount of static variables, not all of which are initialized to their default values (e.g. I have a boolean I initialize to true, a Set I initialize to a new Set(), etc.). This class is somewhat like a controller, that operates on other classes. After it's done operating on a class, I'd like to reinitialize all of its static variables to their original values using (if it exists) something that's a part of the java API, so that I don't have to make a "reinitializeClassVariables()" method with about a dozen variables in it that would need to be updated every time I make any changes to the static variables declared in the class. Any ideas?
我有一个类,它有相当数量的静态变量,并不是所有的都被初始化为它们的默认值(例如,我有一个布尔值我初始化为真,一个 Set 我初始化为一个新的 Set() 等)。这个类有点像一个控制器,它对其他类进行操作。在完成对类的操作后,我想使用(如果存在)作为 java API 一部分的东西将其所有静态变量重新初始化为其原始值,这样我就不必制作“reinitializeClassVariables ()" 方法,其中包含大约十二个变量,每次我对类中声明的静态变量进行任何更改时都需要更新这些变量。有任何想法吗?
采纳答案by PeterMmm
No, nothing build-in. You can do something with reflection or byte code manipulation, but it is not worth and makes all more complicated. Maybe you can refactor the static variables into a new class and then reset with a new instance "when done".
不,没有任何内置。你可以用反射或字节码操作来做一些事情,但它不值得,而且会使一切变得更加复杂。也许您可以将静态变量重构为一个新类,然后在“完成后”使用新实例重置。
回答by aioobe
After it's done operating on a class, I'd like to reinitialize all of its static variables to their original values
完成对类的操作后,我想将其所有静态变量重新初始化为其原始值
Seriously sounds like you would be better of with instancevariables. Then you could just create a new instance of your class (or a class containing your parameters) using new
, and all variables would be initialized to their initial values. Something like this:
说真的,你最好使用实例变量。然后,您可以使用 来创建您的类(或包含您的参数的类)的新实例new
,并且所有变量都将被初始化为其初始值。像这样的东西:
// All parameters (static if you so like)
static ControlParams controlParams = new ControlParams();
...
// Reset parameters
controlParams = new ControlParams();
something that's a part of the java API, so that I don't have to make a
reinitializeClassVariables()
这是 java API 的一部分,这样我就不必制作
reinitializeClassVariables()
No, there's no such thing in the API (actually, it would have to be part of the language specification I believe). The use of static variables is simply a really bad choice in your use case.
不,API 中没有这样的东西(实际上,我认为它必须是语言规范的一部分)。在您的用例中,使用静态变量只是一个非常糟糕的选择。