我是靠谱客的博主 甜蜜蜜蜂,最近开发中收集的这篇文章主要介绍Groovy 中的 with,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

in Java 

 

// PrintIndependenceDay.java

import java.util.Calendar;
import java.util.Date;

public class PrintIndependenceDay {

  public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.MONTH, Calendar.JULY);
    calendar.set(Calendar.DATE, 4);
    calendar.set(Calendar.YEAR, 1776);
    Date time = calendar.getTime();
    System.out.println(time);
  }
}

 in Groovy:

 

 

// PrintIndependenceDay.groovy

def calendar = Calendar.instance
calendar.with {
  clear()
  set MONTH, JULY
  set DATE, 4
  set YEAR, 1776
  println time
}

 每个 Groovy闭包有个与其关联的delegate(代理人).

 

 

// define a closure
def myClosure = {
  // call a method that does not exist
  append 'Jeff'
  append ' was here.'
}

// assign a delegate to the closure
def sb = new StringBuffer()
myClosure.delegate = sb

// execute the closure
myClosure()

assert 'Jeff was here.' == sb.toString()

 换一种写法:

 

 

def closure = {
  clear()
  set MONTH, JULY
  set DATE, 4
  set YEAR, 1776
  println time
}
def calendar = Calendar.instance
closure.delegate = calendar
closure()

 Another bit of info that is missing here is the strategy that a closure uses to decide when to send method calls to the delegate. Each Groovy closure has a resolveStrategy associated with it. This property determines how/if the delegate comes in to play. The 4 possible values for the resolveStrategy are OWNER_FIRST, DELEGATE_FIRST, OWNER_ONLY and DELEGATE_ONLY (all constants defined in groovy.lang.Closure). The default is OWNER_FIRST. Consider the owner to be the "this" wherever the closure is defined. Here is a simple example...

 

 

 

class ResolutionTest {
    
    def append(arg) {
        println "you called the append method and passed ${arg}"
    }
    
    def doIt() {
        def closure = {
            append 'Jeff was here.'
        }
        
        def buffer = new StringBuffer()
        
        closure.delegate = buffer
        
        // the append method in this ResolutionTest
        // will be called because resolveStrategy is
        // OWNER_FIRST (the default)
        closure()
        
        // give the delegate first crack at method
        // calls made inside the closure
        closure.resolveStrategy = Closure.DELEGATE_FIRST
        
        // the append method on buffer will
        // be called because the delegate gets
        // first crack at the call to append()
        closure()
    }
    
    static void main(String[] a) {
        new ResolutionTest().doIt()
    }
}

 运行结果:

you called the append method and passed Jeff was here.

 

 来源:

http://java.dzone.com/news/getting-groovy-with-with

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

最后

以上就是甜蜜蜜蜂为你收集整理的Groovy 中的 with的全部内容,希望文章能够帮你解决Groovy 中的 with所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(33)

评论列表共有 0 条评论

立即
投稿
返回
顶部