当前位置: 首页 > 知识库问答 >
问题:

JAVAlang.ClassCastException:模型类不能强制转换为模型类

吕向阳
2023-03-14

从上面的标题来看,目前我遇到了一个问题,即无法从一个模型类转换到另一个模型类。我写的代码有问题吗?请随时向我询问更多信息。非常感谢。

我怀疑:

这种方法“selectTheOldFnException”有一些错误,那就是使用了hibernate,但我不确定这个理论。

REST控制器

    @RequestMapping(value = "/runMatching/{id}", method = RequestMethod.GET, params = "actionRun")
public String runMatching(@PathVariable(required = true, name = "id") long id) {

    System.out.println("the id is: " + id);

            if (fileExist = true) {

                //upload to db
                int uploadDB = dmttDAO.uploadListToDB(filePath);

                try {

                    //int result = matchingEngine.execute();
                    matchingEngine.execute();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            } else {

                break;
            }
        }
    }

    return "redirect:/excpMonitor";

}

使用HIBERNATE-MatchingEngine选择POJO。班

package com.portal.dmtt.match;

import com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception;
import com.portal.dmtt.model.exceptionMonitoring.FN_Result_Set;
import com.portal.dmtt.model.exceptionMonitoring.config.FN_FR_new_Location;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.List;

public class MatchingEngine {

    private final Logger logger = Logger.getLogger(MatchingEngine.class);


    private List<FN_Old_Exception> fnOldExceptionList;

    private List<FN_Result_Set> fnResultSetList;

    private List<FN_FR_new_Location> fnFrNewLocationList;

    private FN_Result_Set theFnResultSet;

    private FN_Old_Exception theFnOldException;

    public int execute() {

        int result = 0;

        System.out.println(">>>>>>>>>>>>>>>>Start Matching Engine<<<<<<<<<<<<<<<< ");

        System.out.println("Start: selectTheOldFnException ");
        result = selectTheOldFnException();
        if (result < 0) {
            logger.error("[Problem method at selectTheOldFnException]. Result: " + result);

            return -1;
        }

        System.out.println("Start: selectTheConfigurationFN ");
       // result = selectTheConfigurationFN();
        if (result < 0) {
            logger.error("[Problem method at selectTheOldFnException]. Result: " + result);

            return -2;
        }

        System.out.println("Start: matchFN ");
        //result = matchFN();
        if (result < 0) {
            logger.error("[Problem method at matchFN]. Result: " + result);

            return -3;
        }

        System.out.println("Start: theFnResultSet ");
        //result = writeItemToDb(theFnResultSet);
        if (result < 0) {
            logger.error("[Problem method at write item to db]. Result: " + result);

            return -4;
        }

        System.out.println("Start: findNewFN ");
        //result = findNewFN();
        if (result < 0) {
            logger.error("[Problem method at findNewFN]. Result: " + result);
            return -5;
        }

        System.out.println(">>>>>>>>>>>>>>>>End Matching Engine<<<<<<<<<<<<<<<< ");

        return result;
    }

    /**
     * Select the old fn Exception
     *
     * @return
     */
    private int selectTheOldFnException() {

        int result = 0;

        // create session factory
        SessionFactory factory = new Configuration().configure("hibcfg.eMonitor.xml").addAnnotatedClass(FN_Old_Exception.class).buildSessionFactory();

        // create a session
        Session session = factory.openSession();

        try {
            String Query1 = "from FN_Old_Exception";

            // start a transaction
            session.beginTransaction();

            // query current reported watch list
            fnOldExceptionList = session.createQuery(Query1).list();

            // commit transaction
            session.getTransaction().commit();

            result = fnOldExceptionList.size();

            //System.out.println(fnOldExceptionList.toString());

            for (int i = 0; i < result; i++) {

                System.out.println("selectTheOldFnException ---->>>" + fnOldExceptionList.get(i).toString());
            }

        } catch (SessionException e) {

            logger.fatal("Select selectFnException_New: Caught an Exception" + e.getMessage());

        } finally {

            session.close();
            factory.close();

        }

        return result;

    }

    /**
     * match FN based on parameter
     *
     * @return
     */
    private int matchFN() {

        int result = 0;

        result = fnOldExceptionList.size();
        int sizeFNConfiguration = fnFrNewLocationList.size();

        for (int j = 0; j < sizeFNConfiguration; j++) {

            String matchSpId = fnFrNewLocationList.get(j).getMatch_SP_Id();
            String matchLocId = fnFrNewLocationList.get(j).getMatch_Loc_Id();
            String remarks = fnFrNewLocationList.get(j).getRemarks();


            theFnOldException = new FN_Old_Exception();

            for (int i = 0; i < result; i++) {

                if (((fnOldExceptionList.get(i).getSp_Id().equals(matchSpId))) && ((fnOldExceptionList.get(i).getLoc_Id().equals(matchLocId)))) {

                    // set the new remarks after hit the logic
                    fnOldExceptionList.get(i).setRemarks(remarks);

                    String spId = fnOldExceptionList.get(i).getSp_Id();
                    String locId = fnOldExceptionList.get(i).getLoc_Id();
                    String status = fnOldExceptionList.get(i).getXfer_Xmit_Status();
                    String fileName = fnOldExceptionList.get(i).getXfer_File_Name();
                    String updateTS = fnOldExceptionList.get(i).getUpdate_Ts();
                    String yymm = fnOldExceptionList.get(i).getYYMM();
                    String Remarks = fnOldExceptionList.get(i).getRemarks();

                    //display message
                    //System.out.println("matchFN --->>>" + fnOldExceptionList.get(i).toString());

                    theFnResultSet = new FN_Result_Set(spId, locId, status, fileName, updateTS, yymm, Remarks);

                    writeItemToDb(theFnResultSet);
                }
            }
        }

        return result;
    }

    /**
     * SAVE-
     * all result to the new table (FN_Result_Set)
     *
     * @return
     */
    public int writeItemToDb(FN_Result_Set fn_result_set) {

        int result = 0;

        // create session factory
        SessionFactory factory = new Configuration().configure("hibcfg.eMonitor.xml").addAnnotatedClass(FN_Result_Set.class).buildSessionFactory();
        // create a session
        Session session = factory.openSession();

        try {

            session.beginTransaction();

            session.saveOrUpdate(fn_result_set);

            session.getTransaction().commit();

        } catch (HibernateException ex1) {
            ex1.printStackTrace();

        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {

            session.close();
            factory.close();

        }

        return result;
    }

    /**
     * differentiate between two entity
     *
     * @return
     */
    private int findNewFN() {

        int result = 0;

        result = fnOldExceptionList.size();

        for (int i = 0; i < result; i++) {

            if (fnOldExceptionList.get(i).getRemarks() == null) {

                String spId = fnOldExceptionList.get(i).getSp_Id();
                String locId = fnOldExceptionList.get(i).getLoc_Id();
                String status = fnOldExceptionList.get(i).getXfer_Xmit_Status();
                String fileName = fnOldExceptionList.get(i).getXfer_File_Name();
                String updateTS = fnOldExceptionList.get(i).getUpdate_Ts();
                String yymm = fnOldExceptionList.get(i).getYYMM();
                String Remarks = "New Location";

                theFnResultSet = new FN_Result_Set(spId, locId, status, fileName, updateTS, yymm, Remarks);

                writeItemToDb(theFnResultSet);

            }
        }

        return result;
    }

    /**
     * select the configuration selected FN from database
     *
     * @return
     */
    private int selectTheConfigurationFN() {


        int result = 0;

        // create session factory
        SessionFactory factory = new Configuration().configure("hibcfg.eMonitor.xml").addAnnotatedClass(FN_FR_new_Location.class).buildSessionFactory();

        // create a session
        Session session = factory.openSession();

        try {
            String Query1 = "from FN_FR_new_Location";

            // start a transaction
            session.beginTransaction();

            // query current reported watch list
            fnFrNewLocationList = session.createQuery(Query1).list();

            // commit transaction
            session.getTransaction().commit();

            result = fnFrNewLocationList.size();

            //System.out.println(fnOldExceptionList.toString());

            for (int i = 0; i < result; i++) {

                System.out.println("selectTheOldFnException ---->>>" + fnFrNewLocationList.get(i).toString());
            }

        } catch (SessionException e) {

            logger.fatal("Select fnFrNewLocationList : Caught an Exception" + e.getMessage());

        } finally {

            session.close();
            factory.close();

        }

        return result;

    }

}

POJO班

package com.portal.dmtt.model.exceptionMonitoring;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "fn_old_exception")
public class FN_Old_Exception {

    @Id
    @Column(name = "id")
    private int Id;

    @Column(name = "Sp_Id")
    private String Sp_Id;

    @Column(name = "Loc_Id")
    private String Loc_Id;

    @Column(name = "Xfer_Xmit_Status")
    private String Xfer_Xmit_Status;

    @Column(name = "Xfer_File_Name")
    private String Xfer_File_Name;

    @Column(name = "Update_Ts")
    private String Update_Ts;

    @Column(name = "YYMM")
    private String YYMM;

    @Column(name = "Remarks")
    private String Remarks;

例外代码

java.lang.ClassCastException: com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception cannot be cast to com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception
at com.portal.dmtt.match.MatchingEngine.selectTheOldFnException(MatchingEngine.java:125)
at com.portal.dmtt.match.MatchingEngine.execute(MatchingEngine.java:49)
at com.portal.dmtt.match.MatchingEngine.finalExecution(MatchingEngine.java:37)
at com.portal.dmtt.controller.ExcpMonitorController.runMatching(ExcpMonitorController.java:236)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

共有2个答案

施念
2023-03-14

归功于@AndyWilkinson

禁用SpringBoot开发工具:

<!--
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
-->
都浩淼
2023-03-14

这里您使用的是两个同名的不同类FN_Old_Exception

这两个类使用同一个包在不同的jar文件中

com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception 

需要看到完整的代码库来解决冲突,你能分享吗?

 类似资料:
  • 我将调用(used)的响应传递给一个类,并尝试将其强制转换到我的模型类。由于我对调用使用的是registfit,因此它在使用GSON将其转换为模型类对象之前,根据服务器的响应生成一个链接的hashmap。(这就是我所理解的,如果我错了请纠正我)。我已经附加了一个使用response对象进行调试时可以看到的图像。如何将此响应转换为我的模型类或类型对象的对象。当我试图将类型对象强制转换到活动中的模型类

  • 我正在尝试初始化菜单上的自定义搜索工具(3d库),但我得到了错误。 但这无助于第136行对应于 菜单的xml

  • 强制类型转换 隐式类型转换:隐式类型转换又称为自动类型转换,隐式类型转换可分为三种:算术转换、赋值转换和输出转换。 显式类型转换:显式类型转换又称为强制类型转换,指的是使用强制类型转换运算符,将一个变量或表达式转化成所需的类型,这种类型转换可能会造成数据的精度丢失。 数据有不同的类型,不同类型数据之间进行混合运算时必然涉及到类型的转换问题。 转换的方法有两种: 自动转换(隐式转换):遵循一定的规则

  • 我正在尝试在RecyclerView中添加搜索过滤功能。但应用程序因以下错误而崩溃: 科特林。TypeCastException:null不能转换为非null类型kotlin。收藏。请登录com。卡贝拉什。电影。用户界面。PostListAdapter$searchFilter$1。在android上发布结果(PostListAdapter.kt:87)。小装置。筛选$ResultsHandler

  • 问题内容: 我在一个新项目中将Swift样板代码用于Core Data。我的文件有一个定义的单一实体()和一个属性()。 我有一个看起来像这样的文件: 当我运行它时,它起作用: 我什至可以进入iOS模拟器正在使用的SQLite数据库,并确认已添加该行。 但是,当我运行与上面完全相同的代码,但使用而不是时,出现了与…行关联的错误消息,导致崩溃。如果我继续执行,则每次执行线程1时它都会到达并位于线程1

  • 问题内容: 我有以下两节课: 和: 当我运行测试时,一切都是笨拙的。如果我将类型参数化更改为: 编译器抱怨,报告: 错误:类型不兼容的整数不能转换为T number = new Integer(11); 其中T是类型变量T扩展了在方法getSomeValue(boolean)中声明的Object 它同样对Double有所抱怨。为什么? 编辑:我犯了一个错误。这实际上是有效的代码。 现在我明白了@S