如何在地图中使用泛型类型?

时间:2016-06-06 09:45:58

标签: java generics

以前,我为一个名为Address的特定实体类编写了一个方法,这里是代码:

private List<AddLuceneWork> buildAddLuceneWorks(List<Address> addresses) {
    List<AddLuceneWork> addWorks = new LinkedList<>();
    session = em.unwrap(Session.class);
    searchIntegrator = ContextHelper.getSearchintegrator(session);
    entityIndexBinding = searchIntegrator
            .getIndexBindings()
            .get(Address.class);  // specific type
    // ...
    return addWorks;
}

现在,我希望输入是通用的,这样无论处理什么实体都可以。但我之前没有使用过类型,我也不知道如何正确使用它:

private <T> List<AddLuceneWork> buildAddLuceneWorks(List<T> entities) {
    List<AddLuceneWork> addWorks = new LinkedList<>();
    session = em.unwrap(Session.class);
    searchIntegrator = ContextHelper.getSearchintegrator(session);
    entityIndexBinding = searchIntegrator
            .getIndexBindings()
            .get(Address.class);  // <- how to change it to generic ?
    // ...
    return addWorks;
}

我尝试了以下方法,但他们没有工作:

  • .get(T);
  • .get(T.class);
  • .get(clazz.getClass());其中Class<T> clazz = null;

1 个答案:

答案 0 :(得分:4)

由于类型删除private List buildAddLuceneWorks(List entities) { 的代码实际上是

Class

这样它无法工作,您需要添加private <T> List<AddLuceneWork> buildAddLuceneWorks(List<T> entities, Class<T> clazz) { 类型的附加参数,以明确提供预期类型:

get(Address.class)

然后get(clazz)将为<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>JerseyRESTService</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.healthouts.webservices</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JerseyRESTService</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <security-constraint> <web-resource-collection> <web-resource-name>Hidocs</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <session-config> <session-timeout> 60 </session-timeout> </session-config> <welcome-file-list> <!--<welcome-file>LoginForm1.jsp</welcome-file>--> <welcome-file>homepage.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>404</error-code> <location>/pages/error404.jsp</location> </error-page> </web-app>