Poles
Poles

Reputation: 3682

"cannot be cast" in Spring

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)

Upvotes: 0

Views: 1414

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280030

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.

Upvotes: 2

Related Questions