由于 Eclipse IDE 导致的 Java 通用问题

标签 java eclipse maven generics spring-ioc

我已经安装了eclipse:

Eclipse Java EE IDE for Web Developers.
Version: Oxygen.2 Release (4.7.2)
Build id: 20171218-0600

java version is:

java -version
java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)

I imported project here. Project correctly builds with maven and correctly run. But my eclipse gives me error because of COMPILATION ERROR. I know what is COMPILATION ERROR but it is not, I know that is eclipse issue to handle generics.

To be sure that nothing broken I used mvn via terminal - it works correctly also but not in eclipse.

Corrupted Code example

@Component
public class PagingServiceBuilder<T extends DateTimeApi> {
    @Autowired
    private PagingServiceBuildHelper<?> pagingServiceBuildHelper;

    @NotNull
    private List<DateTimeApi> cutEventsPortion(Pageable pageable, List<DateTimeApi> events,
                                               PageableDirection direction) {
        if (pageable.getPageSize() > Constants.DEFAULT_PAGE_SIZE) {
            List<DateTimeApi> sortedEvents = pagingServiceBuildHelper.sortByStartDate(events, direction);
            return getEventToBeReturnedInPageObject(sortedEvents, pageable);
        }
        return events;
    }
...
}

@Component
public class PagingServiceBuildHelper<T extends DateTimeApi> {

    List<T> sortByStartDate(List<T> eventDtoList) {
        return sortByStartDate(eventDtoList, PageableDirection.FORWARD);
    }
...
}

Eclipse 在 sortByStartDate 方法调用上出错。

我知道这个问题一般不在于 Eclipse,看来我的配置失败了(我认为这个问题可能会出现在任何免费的 IDE 中)。我希望获得如何解决该问题的建议。我可以使用终端,但我更喜欢在开发时使用 IDE 来构建和测试项目。

附注

如果我错过了一些有用的细节,请告诉我。

添加更多详细信息

我可以使用 eclipse Java Application 配置运行项目,没有任何问题,但不能使用 eclipse maven 插件。无论如何,maven 通过终端正确处理它。

最佳答案

对我来说,这看起来像是一个编译错误。您的 pagingServiceBuildHelper 的泛型参数为 ?,因此无论如何,在 sortByStartDate 方法的上下文中 T 都是未知的作为参数传递的内容。

如果可能的话,您可以将该方法设为静态,因此 T 将从传入的参数派生(这似乎是您想要实现的目标):

public static <X> List<X> sortByStartDate(List<X> eventDtoList) {
  return sortByStartDate(eventDtoList, PageableDirection.FORWARD);
}

当然,对于被调用的两参数 sortByStartDate 方法也是如此。

或者,如果您不想使其静态,泛型参数仍然应该是方法本地的:

@Component
public class PagingServiceBuildHelper {

    public <T extends DateTimeApi> List<T> sortByStartDate(List<T> eventDtoList) {
        return sortByStartDate(eventDtoList, PageableDirection.FORWARD);
    }
...
}

关于由于 Eclipse IDE 导致的 Java 通用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48076680/

相关文章:

java - 如何从 eclipse 调试 hadoop mapreduce 作业?

java - maven 3.3 支持 Websphere 8.5.5 - pom.xml

java - Maven Appassembler 插件 - stdout 和/或 stderr 重定向

json - 如何使用 Elasticsearch Java API 编写查询,其中 JSON 列表中的元素包含 List<> 中的一些元素?

Java 程序在 Microsoft Server 上每个用户一个进程

java - 不幸的是您的应用程序已停止

Eclipse 注释掉代码的快捷方式不再起作用

java - 如何获取当前的maven目标版本

java - 依赖项未与项目一起编译(Maven)

java - java 将字符串转换为日期