views:

287

answers:

2

I have, a Starter.class which updates some classes when needed, then instantiate and runs a Client class.
Is it possible (if yes, how) for the instance of Class to know if it has been modified since the last call? The modification is only a minor one and most of the methods stay identical.

May be getting the date of last modification of Client.class is the solution? Is that possible?

+1  A: 

What do you mean by modified? As in have any properties changed?

One way that is possible that I've done before, is creating a deep clone of the object using the Serialization API.

ie: create an ObjectOutputStream, and write the object into a ByteArrayOutputStream. Now, you have a set of bytes which is a serialized version of the object at a given point in time.

When you want to see if it has changed, you can do the same thing, and compare the two byte arrays.

The potentional problems with this are:
1) The object needs to be serializable
2) If your object has another object as a property and that object changes, the parent object will be considered changed too. (Though, this may be desired.)

Here's some code:

private static byte[] getObjectBytes(Object object) throws IOException {
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  new ObjectOutputStream (output).writeObject( object );
  output.flush();
  return output.toByteArray();
}

// These go in the object
private byte[] digest;
public void mark() {
  digest = getObjectBytes(this);
}

public boolean hasChanged() {
  return !Arrays.equals(getObjectBytes(this), digest);
}
Milan Ramaiya
+1  A: 

I assume you mean the following situation.

  • Class A1 associates an instance: a1
  • Starter updates a1 to assoicate with A2 (A2 is version 2 of A1)

In order to do this, don't you already have a special class loader? If you create the special class loader, why can't you use the class loader to track last modified time? Are you using OSGi to handle this?

PS.

@Burkhard, if the class file can be changed between instantiations, a class loader in your framework is likely doing the job for you. The default class loader does not reload classes. One solution is to extend that ClassLoader.loadClass(String) method to also record the last updated time after calling the super.loadClass(String). Of course, you have to override your custom class loader in the framework (most Open source frameworks support it). However, I wouldn't suggest to do trick like serializing the class object periodically to figure it is changed and then record the time. It's expensive

Oscar Chan
I did not create the class-loader, nor the update method.
Burkhard