1 回答
TA贡献1765条经验 获得超5个赞
在这种情况下,您应该比较类名而不是使用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);
}
添加回答
举报