序列化后,Instanceof对于相同的类返回false

时间:2018-10-31 22:00:30

标签: java spring class serialization classloader

在org.springframework.security.oauth2.common.util.SerializationUtils在Spring Boot应用程序中更快的XML反序列化之后,Instanceof对于同一个类返回false。

new ObjectMapper().readValue(serialized, User.class);

班级

public class User implements Serializable {//...
}

由于新对象getClass()。getClassloader()返回了不同的类加载器,如何解决此问题并广播问题?

1 个答案:

答案 0 :(得分:1)

在这种情况下,您应该比较类名,而不要使用instanceof。即使这些类是由不同的类加载器加载的,规范名称也将相同:

public boolean haveSameCanonicalName(Object object, Class<?> clazz) {
     String actualClassName = object.getClass().getCanonicalName();
     String expectedClassName = clazz.getCanonicalName();
     return actualClassName.equals(expectedClassName);
}

然后您可以像这样使用它:

if (haveSameCanonicalName(user, User.class)) {
    // Do something here
}

更新:

如果仍然需要投射对象,则有一种解决方法:

 public class CrossCastUtils {

    private final ObjectOutputStream oos;
    private final ObjectInputStream ois;

    public CrossCastUtils() throws IOException {
        final PipedOutputStream pos = new PipedOutputStream();
        final PipedInputStream pis = new PipedInputStream(pos);
        oos = new ObjectOutputStream(pos);
        ois = new ObjectInputStream(pis);
    }

    public <T> T cast(Object object) throws IOException, ClassNotFoundException {
        oos.writeObject(object);
        oos.flush();
        return (T) ois.readObject();
    }

尝试运行此测试:

@Test
public void testCrossCast(){
    Object initial = ... // retrieve it as you did before
    User result = CrossCastUtils.cast(initial);

    assertFalse(initial instanceof User);
    assertTrue(result instanceof User);
}