i have read lot of oline articles and couldnt find an answer and i have tried to make it correct and not able to do it.
Can anyone help,how to initialize generics in bean file and make it work?
Config File
<?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.xsd">
<bean id="collectionDemo" class="com.prashant.Collections6.CollectionDemo">
<constructor-arg index="0" type="String" value="google"/>
<constructor-arg index="1" type="String" value="gooogle"/>
</bean>
</beans>
CollectionDemo.java
public class CollectionDemo<T> {
private T id,phoneNumber;
public CollectionDemo(T id, T phoneNumber) {
super();
this.id = id;
this.phoneNumber = phoneNumber;
}
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
public T getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(T phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public String toString() {
return "CollectionDemo [id=" + id + ", phoneNumber=" + phoneNumber
+ "]";
}
}
ColleactionApp.java
package com.prashanth.Collections6;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class ColleactionApp {
public static void main(String[] args) {
ApplicationContext app=new FileSystemXmlApplicationContext
("/src/main/java/com/prashanth/Collections6/beans.xml");
CollectionDemo<String> coll=(CollectionDemo<String>) app.getBean("collectionDemo");
System.out.println(coll);
}
}
The issue you've posted in the comments is because of a typo
<bean id="collectionDemo" class="com.prashant.Collections6.CollectionDemo">
should be
<bean id="collectionDemo" class="com.prashanth.Collections6.CollectionDemo">
assuming
package com.prashanth.Collections6;
is the correct package name.
The "issue" with generics is
<constructor-arg index="0" type="String" value="google"/>
<constructor-arg index="1" type="String" value="gooogle"/>
Spring will use the type
you specified to match constructor arguments. But your class constructor's arguments are not of type String
, they are of type T
, which erase to Object
. Either change it to
<constructor-arg index="0" type="Object" value="google"/>
<constructor-arg index="1" type="Object" value="gooogle"/>
or remove the type
altogether.
Generics are a compile time concept. They do not exist at runtime. But Spring uses reflection at runtime to generate beans. There's no type argument to specify for your generic types in the bean definitions.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments