编程语言
首页 > 编程语言> > java – JAXB:类强制转换异常,但类具有相同的名称

java – JAXB:类强制转换异常,但类具有相同的名称

作者:互联网

我有一个有趣的问题.

当我启动glassfish服务器时,每个人都可以正常工作.但是,我更改了一些代码并发布了服务器,并运行了我的客户端(SistemGirisClientKullaniciDogrula).应用程序抛出此异常:

java.lang.ClassCastException: tr.com.app.Kullanici cannot be cast to tr.com.app.Kullanici.

有趣的是,在Glassfish服务器重启后,应用程序运行正常.

我正在使用restlet-spring-hibernate.我还使用JAXB(org.restlet.ext.jaxb.jar)将XML转换为Java对象.我的应用服务器是Glassfish v3.0

配置细节

> restlet 2.0.5
>春天3.0.5
> hibernate 3.3.2
> glassfish v3.0

客户类(仅供测试)

import java.io.IOException;

import org.restlet.Client;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.ext.jaxb.JaxbRepresentation;

public class SistemGirisClientKullaniciDogrula {

    public static void main(String[] Args) throws IOException {

        String url = "http://localhost:8080/Project/sistemgirisws";

        Client client = new Client(Protocol.HTTP);

        Kullanici kullanici = new Kullanici();
        kullanici.setKodu("1");

        JaxbRepresentation<Kullanici> jaxbRepresentationSendingKullanici= new JaxbRepresentation<Kullanici>(MediaType.APPLICATION_XML, kullanici);

        Request request = new Request(Method.GET, url, jaxbRepresentationSendingKullanici);
        Response response = client.handle(request);

        JaxbRepresentation<Kullanici> kullaniciResponse = new JaxbRepresentation<Kullanici>(response.getEntity(), Kullanici.class);
        kullanici = kullaniciResponse.getObject();

        System.out.println("kullanici id : " + kullanici.getId());
    }
}

网络服务

public class ProjectWebService {

/**
 * 
 * @param representation
 * @return
 */
@Get
public Representation getKullanici(Representation representation) {

    JaxbRepresentation<Kullanici> jaxbRepresentation = new JaxbRepresentation<Kullanici>(representation, Kullanici.class);

    Kullanici kullanici = new Kullanici();

    try {

        kullanici = jaxbRepresentation.getObject(); //THIS LINE THROW java.lang.classCastException tr.com.app.Kullanici cannot be cast to tr.com.app.Kullanici.

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        kullanici = sistemGirisBusinessManager.kullaniciDogrula(kullanici);

        getResponse().setStatus(Status.SUCCESS_OK);
        return new JaxbRepresentation<Kullanici>(MediaType.APPLICATION_XML, kullanici);

    } catch (Exception exception) {

        exception.printStackTrace();
        getResponse().setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED);
        return new JaxbRepresentation<MesajList>(MediaType.APPLICATION_XML, sistemGirisBusinessManager.getMesajList());

    }
}
}

有谁知道问题是什么?

解决方法:

这可能是一个类加载问题.在Java中,如果两个类加载器加载了相同的类,则将其视为两个不同的类.在这种情况下,您的转换将失败,因为在JVM中您似乎将一种类型转换为另一种不在继承树中的类型.

必须发生的是,当您修改类时,它会被加载到不同的类加载器中,而Web服务使用原始类.

标签:classcastexception,java,jaxb
来源: https://codeday.me/bug/20190903/1796913.html