How to get class of generic type in Spring

你。 提交于 2020-04-16 19:46:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!