在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()返回不同的类加载器,因此如何解决此问题并强制转换问题?

最佳答案

在这种情况下,您应该比较类名,而不要使用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);
}

09-28 02:14