Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re-initialize the static variables of a class to their original values java

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?

like image 878
Peter Berg Avatar asked Jan 19 '23 09:01

Peter Berg


2 Answers

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 instance variables. 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:

// 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()

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.

like image 199
aioobe Avatar answered Jan 20 '23 21:01

aioobe


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".

like image 36
PeterMmm Avatar answered Jan 20 '23 21:01

PeterMmm