我正在开发一个在 Java 1.7 上运行的应用程序。我需要用 SpringFramework 重写一些用 Java 1.8 编写的代码。不幸的是,我不熟悉较新的版本,并且不知道如何重写此代码以与 Java 7 一起使用...
下面是代码部分。
ConfigRepo:
public class ConfigRepo extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repoRestConfig) {
repoRestConfig.withEntityLookup().forRepository(IConfigRepo.class, (Config config) -> {
ConfigPK pk = new ConfigPK();
pk.setScope(config.getId().getScope());
pk.setKey(config.getId().getKey());
return pk;
}, IConfigRepo::findOne);
}
IConfigRepo:
public interface IConfigRepo extends CrudRepository<Config, ConfigPK> {}
编辑: 添加了我的代码。
我不确定我是否正确地完成了其中的一部分。我不知道这个Config配置应该如何传递。我也不知道应该如何处理这个方法引用...
我的版本:
public class ConfigRepo extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repoRestConfig) {
repoRestConfig.withEntityLookup().forRepository(IConfigRepo.class, new Config() {
public ConfigPK prepareConfigPK(Config config) {
ConfigPK pk = new ConfigPK();
pk.setScope(config.getId().getScope());
pk.setKey(config.getId().getKey());
return pk;
}, IConfigRepo::findOne);
}
最佳答案
函数forRepository
似乎接受三个论点:
- 一个
Class<IConfigRepo>
接口(interface)
Converter<Config, ConfigPK>
的实例:public interface Converter<Config, ConfigPK> { ConfigPK convert(Config config); }
它实际上是一个通用接口(interface),但我插入了您在那里使用的类型。
另一个功能接口(interface)的实例
Lookup<IConfigRepo, ID>
public interface Lookup { Object lookup(IConfigRepo repository, ID identifier) }
又是一个通用接口(interface),但我插入了您使用的类型(
ID
除外)。
因此,两个函数接口(interface)参数都可以重写为匿名类的实例:
// Java 8
(Config config) -> {
ConfigPK pk = new ConfigPK();
pk.setScope(config.getId().getScope());
pk.setKey(config.getId().getKey());
return pk;
}
//Java 7
new Converter<Config, ConfigPK>() {
@Override
public ConfigPK convert(Config config) {
ConfigPK pk = new ConfigPK();
pk.setScope(config.getId().getScope());
pk.setKey(config.getId().getKey());
return pk;
}
}
和
// Java 8
IConfigRepo::findOne
// Java 7
// ??? because I don't know your type for ID
new Lookup<IConfigRepo, ???>() {
@Override
public Object lookup(IConfigRepo repository, ??? identifier) {
return repo.findOne();
}
}
在您的代码中,您可以用我在那里编写的内容替换作为参数的 Java8 样式 lambda 和方法引用
关于java - 将带有方法引用的 lambda 转换为 Java 7 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44628473/