问题描述:

I've noticed this question posed for a related problem with unit testing, but my problem is more general programming, and I wanted some advice.

I'm writing a piece of software that uses Java Reflection to select and vary the value of Fields that are part of a particular library. I then run code related to the library, record the effect the field had, and move on to another Field.

The problem is that I thought the act of initialising the library code reset the fields it needed to run. Turns out it doesn't. And I don't know which fields specifically might've been changed (because there's a lot of them, the library is quite large). So I need a way of resetting all the fields that doesn't involve restarting my entire, Reflection-using code.

I saw in other questions that ClassLoaders might be able to do this, by reloading the affected classes. But the comments also said that this will only work if you created the ClassLoaders that loaded these classes in the first place.

Can anyone suggest any way to reliably reset the static fields of a class in normal Java executions?

网友答案:

I would say, write a static synchronized method for each class resetting all attributes and when ever you call it synchronize on classloader (getClass().getClassloader())

相关阅读:
Top