Reputation: 141
I have many instances of a particular programs running on different machines. Except for downtime to install a new version, the program is running all the time, and during installations, different versions of the program can be running on different machines. But since there are so many different installation I'd like to make sure that data (effectively) serialized from one definition of a class from a particular running producer of the class's is the same as the class definition of the receiver of the data.
So the obvious solution would be to use a serialVerionUID but changing that breaks other stuff and people can forget to update the ID between, and that is not available from the class object itself (object.getClass()). System.identityHashcode() is of no value as well.
So I guess the real question if someone hands you a Class object and you have reference to the expected class object, is there a way to tell if both classes represent the same thing exactly, fields, field definitions, etc. even if the class has exactly the same package and name
Upvotes: 2
Views: 84
Reputation: 425063
You could compare the hashCode()
of the bytes in the .class
file for the class, which you know is available because the class loaded.
Here's some code to get the hash:
public static int getHash(Class<?> clazz) throws IOException {
return Arrays.hashCode(clazz.getClassLoader().getResourceAsStream(clazz.getName().replace(".", "/")).readAllBytes());
}
Upvotes: 1
Reputation: 117
You can. But it has its downsides, you can use reflection to check all properties, methods and internals of your object and compare it to another object to check for equivalence.
Class c = ob.getClass();
for (Method method : c.getMethods()) {
if (method.getAnnotation(PostConstruct.class) != null) {
System.out.println(method.getName());
}
}
Thats for methods.
And you can do the same for fields:
Field[] allFields = SomeClass.class.getDeclaredFields();
Then you can check if they are the same version of a class or not. If the difference is in number of methods or fields, however if the change is inside of a method you can't easily tell una class from the other.
Upvotes: 0