1

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.

v11
  • 2,124
  • 7
  • 26
  • 54

1 Answers1

2

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>
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252