日期:2014-05-19 浏览次数:21115 次
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类对象");
}
}
package com.generic;
public interface GenericInter<T> {
T findById();
}
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;
}
}
<?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>
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();
}
}