0

I tried to run a simple Spring (4.0.0 release) program using Eclipse. But I'm stuck in one place. It says "cannot be cast".

Drawing.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> 

When I tried to execute it it prints:

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) 

1 Answer 1

2

This

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

should be

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

Drawing is not a sub type of Square and therefore cannot be cast to Square.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.