问题
I have a generics class DAO in my spring project,I have to get class of generic T.I know the pure java solution:
class Foo<T> {
final Class<T> typeParameterClass;
public Foo(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
public void bar() {
// you can access the typeParameterClass here and do whatever you like
}
}
But,in spring project,I have to get the Foo from the "ApplicationContext",I can't get Foo by:
Foo<ClassName> foo = new Foo<ClassName>(ClassName.class);
How to get class of generic type in Spring.
回答1:
Spring is able to use constructors with parameters
In java configuration, it is very simple :
@Configuration
public class MyConf {
...
@Bean
private foo() {
return new Foo<ClassName>(ClassName.class);
}
...
}
It is also possible with XML config
<bean id="foo" class="...Foo">
<constructor-arg type="java.lang.Class" value="...ClassName"/>
</bean>
来源:https://stackoverflow.com/questions/26376638/how-to-get-class-of-generic-type-in-spring