日期:2014-05-19  浏览次数:20887 次

Java泛型Spring2.5注入,产生异常,求关注。
我知道在Spring2.5中没有直接支持JAVA泛型的注入支持,在Spring3后能够支持,网上为找到怎么配置的。

现在我贴出我的泛型Spring的实现,然后再说产生的异常。

TestClass1
TestClass2
Java code

package com.entity;

public class TestClass1 {
    public void returnClass() {
        System.out.println("得到了TestClass1类对象");
    }
}


package com.entity;

public class TestClass2 {
    public void returnClass() {
        System.out.println("得到了TestClass2类对象");
    }
}




GenericInter接口
Java code

package com.generic;

public interface GenericInter<T> {
    T findById();
}



实现上面的接口 GenericImpl

Java code

package com.generic;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class GenericImpl<T> implements GenericInter<T> {

    private Class<T> classType;

    public GenericImpl(Class<T> classType) {
        // Type genType = getClass().getGenericSuperclass();
        // Type[] params = ((ParameterizedType)
        // genType).getActualTypeArguments();
        // this.classType = (Class) params[0];
        this.classType = classType;
    }

    @SuppressWarnings("unchecked")
    public T findById() {
        return (T) classType;
    }
}




Spring的applicationContext.xml配置内容
XML code

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="testClass1" class="com.entity.TestClass1" />
    <bean id="testClass2" class="com.entity.TestClass2" />

    <bean id="genericImpl1" class="com.generic.GenericImpl">
        <constructor-arg value="com.entity.TestClass1" />
    </bean>
    <bean id="genericImpl2" class="com.generic.GenericImpl">
        <constructor-arg value="com.entity.TestClass1" />
    </bean>
</beans>


测试入口类
Java code

package com.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.entity.TestClass1;
import com.generic.GenericImpl;

public class Client {
    public static void main(String[] args) {
           /// 采用Spring的注入方式获得泛型后的对象
       /// BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");
       /// GenericImpl impl1 = (GenericImpl) beanFactory.getBean("genericImpl1");

        ///直接访问泛型对象
        GenericImpl<TestClass1> impl1 = new GenericImpl<TestClass1>(TestClass1.class);
        TestClass1 testClass1 = (TestClass1) impl1.findById();
        testClass1.returnClass();
    }
}




上面两种方式都会,输出的结果产生的类型强制转换异常

Exception in thread "main" 求Toplink essentials 教程!该怎么解决