views:

66

answers:

4

Is there a simple way to clear all fields of an instance from a an instance? I mean, I would like to remove all values assigned to the fields of an instance.

ADDED

From the main thread I start a window and another thread which controls state of the window (the last thread, for example, display certain panels for a certain period of time). I have a class which contains state of the window (on which stage the user is, which buttons he already clicked).

In the end, user may want to start the whole process from the beginning (it is a game). So, I decided. So, if everything is executed from the beginning, I would like to have all parameter to be clean (fresh, unassigned).

ADDED

The main thread, creates the new object which is executed in a new thread (and the old thread is finished). So, I cannot create a new object from the old thread. I just have a loop in the second thread.

+1  A: 

There is no other way than setting null to all of them.

As an aside, i find that a particular weird idea. You would have better re-creating a new instance, instead of trying to reset your old one.

Riduidel
+2  A: 

I don't get it. How can you programmatically decide how to clear various fields?

For normal attributes it can be easy (var = null) but what about composite things or collection? Should it be collection = null, or collection.removeAll()?

This question is looking for synctactic sugar that wouldn't make so much sense..

The best way is to write out your own reset() method to customize the behaviour for every single object.. maybe you can patternize it using an

interface Resettable
{
  void reset()
}

but nothing more than that..

Jack
A: 

Is there a simple way to clear all fields of an instance from a an instance? I mean, I would like to remove all values assigned to the fields of an instance.

Yes, just assign a default value to each one of them. It would take you about 20-30 mins. and will run well forever*( YMMV)

Create a method: reset and invoke it

class YourClass {
    int a;
    int b;
    boolean c;
    double d;
    String f;
    // and so on... 
    public void method1(){}
    public void method2(){}
    public void method3(){}
    // etc. 
    // Magic method, reset all the attributes of your instance...
    public void reset(){
        a = 0;
        b = 0;
        c = false;
        d = 0.0;
        f = "";
     }
}

And then just invoke it in your code:

   .... 
   YourClass object = new YourClass();
   Thread thread = YourSpecificNewThread( object );
   thread.start();

   ... // Later on you decide you have to reset the object just call your method:

   object.reset(); // like new

I don't really see where's the problem with this approach.

OscarRyz
A: 

You may use reflection:

Try something like this:

Field[] fields = object.getClass().getDeclaredFields();
for (Field f : fields) {
  f.setAccessible(true);
  f.set(object, null);
}

It's not a beautifull solution, but may work for you.

Kico Lobo