gpt4 book ai didi

java - Spring "cannot be cast"

转载 作者:行者123 更新时间:2023-12-02 06:23:13 25 4
gpt4 key购买 nike

我尝试使用 Eclipse 运行一个简单的 Spring(4.0.0 版本)程序。但我被困在一处。它说“无法施放”。

绘图.java

package org.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Drawing {

public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("org/spring/spring.xml");
Square myBean= (Square) context.getBean("square");
myBean.paint();
}

Square.java

package org.spring;

public class Square {
public void paint() {
System.out.println("Square Drawn");
}
}

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="square" class="org.spring.Drawing">
</bean>
</beans>

当我尝试执行它时,它会打印:

Exception in thread "main" java.lang.ClassCastException: org.spring.Drawing cannot be cast to org.spring.Square
at org.spring.Drawing.main(Drawing.java:10)

最佳答案

这个

<bean id="square" class="org.spring.Drawing">

应该是

<bean id="square" class="org.spring.Square">

Drawing 不是 Square 的子类型,因此无法转换为 Square

关于java - Spring "cannot be cast",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20816933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com