Is it possible to know if a serialVersionUID was automatically generated or not?
I'm wondering whether it's possible to figure out if some s开发者_运维知识库erialVersionUID has been automatically generated (by the JVM) or whether a static one is explictly defined in the class.
Any clue if it's possible to do, and if so how?
Use reflection.Here's an example (I haven't checked the exact contract for the serialVersionUID field, though):
public class SerialTest {
private static class A implements Serializable {
private static final long serialVersionUID = 1L;
}
private static class B implements Serializable {
}
public static void main(String[] args) throws Exception {
System.out.println("A : " + containSerialVersionUID(A.class));
System.out.println("B : " + containSerialVersionUID(B.class));
}
private static boolean containSerialVersionUID(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals("serialVersionUID")
&& field.getType() == Long.TYPE
&& Modifier.isPrivate(field.getModifiers())
&& Modifier.isStatic(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())) {
return true;
}
}
return false;
}
}
Did you try through introspection to check for the field serialUID ? I don't know if the JVM will assign it this way or just store it in a different manner when generating it.
Regards, Stéphane
精彩评论