猿问

序列化后Instanceof为同一个类返回false

在 org.springframework.security.oauth2.common.util.SerializationUtils 在 Spring 启动应用程序中进行 fastxml 反序列化后,Instanceof 为同一类返回 false

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

班级

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

因为新对象 getClass().getClassloader() 返回不同的类加载器,如何解决这个和转换问题?


回首忆惘然
浏览 389回答 1
1回答

POPMUISE

在这种情况下,您应该比较类名而不是使用instanceof. 即使类由不同的类加载器加载,规范名称也将相同:public boolean haveSameCanonicalName(Object object, Class<?> clazz) {&nbsp; &nbsp; &nbsp;String actualClassName = object.getClass().getCanonicalName();&nbsp; &nbsp; &nbsp;String expectedClassName = clazz.getCanonicalName();&nbsp; &nbsp; &nbsp;return actualClassName.equals(expectedClassName);}然后你可以像这样使用它:if (haveSameCanonicalName(user, User.class)) {&nbsp; &nbsp; // Do something here}更新:如果您仍然需要投射对象,则有一种解决方法:&nbsp;public class CrossCastUtils {&nbsp; &nbsp; private final ObjectOutputStream oos;&nbsp; &nbsp; private final ObjectInputStream ois;&nbsp; &nbsp; public CrossCastUtils() throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; final PipedOutputStream pos = new PipedOutputStream();&nbsp; &nbsp; &nbsp; &nbsp; final PipedInputStream pis = new PipedInputStream(pos);&nbsp; &nbsp; &nbsp; &nbsp; oos = new ObjectOutputStream(pos);&nbsp; &nbsp; &nbsp; &nbsp; ois = new ObjectInputStream(pis);&nbsp; &nbsp; }&nbsp; &nbsp; public <T> T cast(Object object) throws IOException, ClassNotFoundException {&nbsp; &nbsp; &nbsp; &nbsp; oos.writeObject(object);&nbsp; &nbsp; &nbsp; &nbsp; oos.flush();&nbsp; &nbsp; &nbsp; &nbsp; return (T) ois.readObject();&nbsp; &nbsp; }尝试运行此测试:@Testpublic void testCrossCast(){&nbsp; &nbsp; Object initial = ... // retrieve it as you did before&nbsp; &nbsp; User result = CrossCastUtils.cast(initial);&nbsp; &nbsp; assertFalse(initial instanceof User);&nbsp; &nbsp; assertTrue(result instanceof User);}
随时随地看视频慕课网APP

相关分类

Java
我要回答