Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java8中的条件lambda执行_Java_Lambda_Java 8 - Fatal编程技术网

Java8中的条件lambda执行

Java8中的条件lambda执行,java,lambda,java-8,Java,Lambda,Java 8,我在Java8中有一个方法create(Environment env),它有多个语句。现在我需要重写这个方法来添加对新的迁移功能的支持 添加对迁移的支持只意味着: 如果Environment env对象的字段migration设置为true不 在create函数中执行一些代码 这就是我包装这些代码块的原因: protected Environment create(Environment env) { statements; if (!env.isForMigrate())

我在Java8中有一个方法
create(Environment env)
,它有多个语句。现在我需要重写这个方法来添加对新的
迁移
功能的支持

添加对
迁移的支持
只意味着:

如果
Environment env
对象的字段
migration
设置为
true
不 在
create
函数中执行一些代码

这就是我包装这些代码块的原因:

protected Environment create(Environment env) 
{
    statements;
    if (!env.isForMigrate()) {
         // executed only if it's NOT a migration
        statements;
        // for example: imh.create(ve)
        // or: newEnv.setAps(env.getAps());
    }
    ...
    statements;
    if (!env.isForMigrate()) {
         // executed only if it's NOT a migration
        statements;
    }
    ...
    and so on...
}
这些代码块遍布
创建
函数。
因此,我必须为多个代码块添加条件执行

在使用lambda表达式的情况下,我能获得一些优势吗?Java8中有任何模式吗

我的意图是这样写:

final Predicate<T> forMigrate = (func) -> {
    // closure for Environment env
    if (env.isForMigrate()) {
        func(); // execute passed statements
    }
}

... 
forMigrate({
    Environment newEnv = apsh().envh().im2aps(ve);
    newEnv.setAps(env.getAps());
    newEnv.setOsId(env.getOsId());
});
forMigration.accept(() -> System.out.println("migrating"));
我将如何用旧的Java 7风格重写它:

protected Environment create(Environment env)
    {
        if(env.getHostname()!=null && env.getHostname().endsWith(".")){
            String normalizedHostname = env.getHostname().substring(0, env.getHostname().length() - 1);
            env.setHostname(normalizedHostname);
        }
        Ve ve = apsh().envh().aps2im(env);
        if (ve.getHostname() == null) {
            ve.setHostname(ve.getName());
        }
        List<String> apps = env.getApps();
        Boolean passwordSet = false;

        // NOTE: Wrap block of code
        if (env.isForMigrate() == false) {
            imh.create(ve);
        }
        ve = imh.getVe(ve.getCustomerId().intValue(), ve.getName());
        if(env.getPassword()!= null && !env.getPassword().isEmpty()){
            try{
                imh.setVePassword(ve.getCustomerId(), ve.getName(), env.getPassword());
                passwordSet = true;
            } catch(Exception ex){
                logger.error("Failed to set password for VE: " +  env.getName(), ex);
            }
        }
        if (!apps.isEmpty()) {
            try {
                imh.setVeApps(ve.getCustomerId().intValue(), ve.getName(), apps);
            } catch (Exception ex) {
                logger.error("Failed to install applications VE: {}", ex);
            }
        }

       // NOTE: Wrap block of code
       if (env.isForMigrate() == false) {
           VeFacade vef = vehFactory.create(ve.getCustomerId(), ve.getName());
           vef.operation("start");
       }

        ve = imh.getVe(ve.getCustomerId().intValue(), ve.getName());
        Environment newEnv = apsh().envh().im2aps(ve);
        // NOTE: Wrap block of code
        if (env.isForMigrate() == false) {
            newEnv.setAps(env.getAps());
            newEnv.setOsId(env.getOsId());
            newEnv.setSample(env.getSample());
        }
        newEnv.setHosting(env.getHosting());
        newEnv.setDomain(env.getDomain());
        newEnv.getStatus().setUptime(Long.valueOf(new Date().getTime()));
        newEnv.setPassword(null);  //prevent password from being saved in DB    
        newEnv.setPasswordSet(passwordSet);
        apsh().envh().fillOsData(newEnv, apsh().teh().getOs(newEnv.getOsId()));
        apsh().envh().synchPublicAddresses(newEnv, ve);
        apsh().dnsh().synchDomainRecords(newEnv);
        logger.info("Environment '{}' successfully created", newEnv.getName());
        return newEnv;
    }
受保护环境创建(环境环境)
{
if(env.getHostname()!=null&&env.getHostname().endsWith(“.”){
字符串normalizedHostname=env.getHostname().substring(0,env.getHostname().length()-1);
环境设置主机名(normalizedHostname);
}
Ve Ve=apsh().envh().aps2im(env);
if(ve.getHostname()==null){
setHostname(ve.getName());
}
List apps=env.getApps();
布尔密码集=false;
//注意:换行代码块
if(env.isForMigrate()==false){
imh.创建(ve);
}
ve=imh.getVe(ve.getCustomerId().intValue(),ve.getName());
如果(env.getPassword()!=null&&!env.getPassword().isEmpty()){
试一试{
setVePassword(ve.getCustomerId(),ve.getName(),env.getPassword());
passwordSet=true;
}捕获(例外情况除外){
logger.error(“未能为VE设置密码:+env.getName(),ex”);
}
}
如果(!apps.isEmpty()){
试一试{
imh.setVeApps(ve.getCustomerId().intValue(),ve.getName(),apps);
}捕获(例外情况除外){
logger.error(“未能安装应用程序VE:{}”,ex);
}
}
//注意:换行代码块
if(env.isForMigrate()==false){
VeFacade vef=vehFactory.create(ve.getCustomerId(),ve.getName());
车辆运行(“启动”);
}
ve=imh.getVe(ve.getCustomerId().intValue(),ve.getName());
环境newEnv=apsh().envh().im2aps(ve);
//注意:换行代码块
if(env.isForMigrate()==false){
newEnv.setAps(env.getAps());
newEnv.setOsId(env.getOsId());
newEnv.setSample(env.getSample());
}
newEnv.setHosting(env.getHosting());
newEnv.setDomain(env.getDomain());
newEnv.getStatus().setUptime(Long.valueOf(new Date().getTime());
newEnv.setPassword(null);//防止在数据库中保存密码
newEnv.setPasswordSet(密码集);
apsh().envh().fillOsData(newEnv,apsh().teh().getOs(newEnv.getOsId());
apsh().envh().synchPublicAddresss(newEnv,ve);
apsh().dnsh().synchDomainRecords(newEnv);
info(“已成功创建环境“{}”,newEnv.getName());
返回新环境;
}

您可以编写如下内容:

private static void forMigrate(Environnement env, Runnable r) {
  if (!env.isForMigrate()) r.run();
}
在您的代码中:

forMigrate(env, () -> {
    newEnv.setAps(env.getAps());
    newEnv.setOsId(env.getOsId());
    newEnv.setSample(env.getSample());
  }
);

这是一个基于您的代码的示例

private static class Environment {
    private String aps;
    private String osId;
    private String sample;
    private boolean forMigrate;

    public String getAps() {
        return aps;
    }
    public void setAps(String aps) {
        this.aps = aps;
    }
    public String getOsId() {
        return osId;
    }
    public void setOsId(String osId) {
        this.osId = osId;
    }
    public String getSample() {
        return sample;
    }
    public void setSample(String sample) {
        this.sample = sample;
    }

    private void forMigration(Environment e, Consumer<Environment> con) {
        if (!e.isForMigrate()) {
            con.accept(e);
        }
    }

    public boolean isForMigrate() {
        return forMigrate;
    }
    public void setForMigrate(boolean isForMigrate) {
        this.forMigrate = isForMigrate;
    }

    protected Environment create(Environment env) {
        Environment newEnv= new Environment();
        List<String> imh=new ArrayList<>();
        forMigration(env, e -> {newEnv.setAps(e.getAps());newEnv.setOsId(e.getOsId()); });
        forMigration(env, e -> {imh.add("test for generic call"); });
        return newEnv;
    }
}
私有静态类环境{
私有字符串AP;
私有字符串osId;
私有字符串样本;
私有布尔型网格;
公共字符串getAps(){
返回AP;
}
公共void setap(字符串ap){
this.aps=aps;
}
公共字符串getOsId(){
返回osId;
}
公共void setOsId(字符串osId){
this.osId=osId;
}
公共字符串getSample(){
返回样品;
}
公共void设置示例(字符串示例){
这个样本=样本;
}
私人空间整合(环境e、消费者con){
如果(!e.isForMigrate()){
con.接受(e);
}
}
公共布尔值isForMigrate(){
返回式格栅;
}
public void setForMigrate(布尔值isForMigrate){
this.forMigrate=isForMigrate;
}
受保护环境创建(环境环境){
环境newEnv=新环境();
List imh=new ArrayList();
formiglation(env,e->{newEnv.setAps(e.getAps());newEnv.setOsId(e.getOsId());});
formiglation(env,e->{imh.add(“测试通用调用”);});
返回新环境;
}
}

使用消费者,您可以在lambda中引用您用于检查的相同环境(如果需要环境)。

我不知道这是否是您的选项,但在
创建
中,您可以编写:

Consumer<Runnable> forMigration = runnable -> {
    if (environment.isForMigrate()) runnable.run();
};

但是,您无法轻松摆脱该函数接口方法调用,因为您只能对函数使用函数调用语法(带括号),而函数调用语法无法捕获调用站点的环境。

您的问题一点也不清楚-您能否用编译的实际代码(带或不带lambda)演示一个示例?我添加了更多细节、原始函数代码和修改后的代码(在Java 7中看起来如何)。谢谢!这与我的意图非常相似。但我如何才能将formiglation编写为create函数中的lambda表达式(甚至是捕获环境env的闭包),而不是环境方法呢?我添加了注释来解释我的困难。@likern根据我对lambda的了解,我不认为这是可能的,或者如果可能的话,我怀疑java7解决方案会更复杂
forMigration.accept(() -> System.out.println("migrating"));