JWorld@TW the best professional Java site in Taiwan
      註冊 | 登入 | 全文檢索 | 排行榜  

» JWorld@TW » Languages on JVM » Groovy  

按列印兼容模式列印這個話題 列印話題    把這個話題寄給朋友 寄給朋友    訂閱主題
reply to topicthreaded modego to previous topicgo to next topic
本主題所含的標籤
無標籤
作者 Groovy Language簡介
popcorny

Jakarta 2%

版主

發文: 752
積分: 20
於 2004-03-24 10:33 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
Groovy Language已經加入JSR 241了,他是完全貼近Java Platform的script language
以下是節錄Groovy - Scripting for Java
希望大家可以初步的了解
此篇已經獲得原作者刊登同意

Introduction
Groovy是設計用來以精簡快速有趣的方式來在Java平台上處理事務,
並且把類似Python Ruby等的強大功能帶到Java的世界裡。
Groovy可以被直譯,也可以被編譯成bytecode,
所以Groovy可以取得跟Java差不多的效能,
這是跟其他script lanaguage是較不一樣的。


Downloading and Installing Groovy
要下載Groovy,請依下列步驟
1. 連到http://groovy.codehaus.org/
2. 點最上面瀏覽列的"download"
3. 點"this site"的連結
4. 選擇要下載的版本

安裝Groovy,請依下列步驟
1. 解開下載檔
2. 把GROOVY_HOME環境變數設到解壓縮的位置
3. 把$GROOVY_HOME/bin (UNIX) 或
%GROOVY_HOME%\bin (Windows)放到PATH的環境變數裡

Running Groovy
分四種
1. Interactive Shell
2. Interactive Swing Console
3. Script File Execution
4. Compiled Script Execution

Some Syntax Details
1. 目標是能夠支援所有的JAVA語法,但是目前還沒完全達到。
2. statement最後的分號是可有可無的
3. 呼叫method旁邊的括號是可有可無的,只要不會造成ambiguous。但是constructor一定要有。
4. "return"也是可有可無的。只要最後一個statement有被執行,則他的值就代表回傳值。
5. Groovy的properties跟method預設皆是public,而非java的pacakge private。
6. 在java.lang groovy.lang groovy.util都是預設被import。

Dynamic Typing
型態對所有varibles、properties、method/closure parameters和
method ruturn type都是可有可無的。它們都是在指定值給他們時才
會真正決定是什麼type。所有type都可以被使用,即使是primitive type。
當有需要時,型別轉換會自動發生在String、primitive type、
wrapper class之間。也因此我們可以把所有type都放在collection中。

Added Methods
Groovy加了一些method在標準的Java類別中,
(如java.lang.Object、java.lang.String)
可以參考http://groovy.codehaus.org/groovy-jdk.html

Groovy Strings
字串可以可以是單引號或是雙引號。當用說引號時,我們可以在
字串中內嵌一些運算式。如以下的例子
1
String toString() { "${name} is ${age} years old." }

而多行的字串可以有三行的方式可以產生,其中最後一個例子是明確指定以下
為文件資料(Here Doc)。EOS代表"End Of String"。
1
2
3
4
5
6
7
8
9
10
11
12
13
    s = "  This string
      spans three \"lines\"
      and contains two newlines."
 
    s = """  This string
      spans three "lines"
      and contains two newlines."""
 
    s = <<<EOS
      This string
      spans three "lines"
      and contains two newlines.
    EOS


Regular Expressions (regex)
使用J2SE1.4的regular expressions,但是多了這三個opeartion
~"pattern" 產生一個Pattern物件且等同於Pattern.compile("pattern").
"text" =~ "pattern" 產生一個Matcher物件且等同於Pattern.compile("pattern").matcher("text").
"text" ==~ "pattern" 回傳true或false,等同於Pattern.compile("pattern").matcher("text").matches().

Groovy Scripts
Groovy scripts是用".groovy"為副檔名的groovy原始檔。他們可以
是不屬於某個class的鬆散statements,可以定義method或是class。
以下是例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// These are loose statements.
println 'loose statement'
myMethod 'Mark', 19
println new MyClass(a1:'Running', a2:26.2)
 
// This is a method definition that
// is not associated with a class.
def myMethod(p1, p2) {
  println "myMethod: p1=${p1}, p2=${p2}"
}
 
// This is a definition of a class that
// has two properties and one method.
class MyClass {
  a1; a2
  String toString() { "MyClass: a1=${a1}, a2=${a2}" }
}


Operator Overloading
Groovy允許某些部分的operator overloading,這些operator會對應到
某些method name,只要實作這些method在你的類別就可以用對應的
operator來呼叫這些method。
Comparison Operators
a == b maps to a.equals(b)
a != b maps to !a.equals(b)
a === b maps to a == b in Java
a <=> b maps to a.compareTo(b)
a > b maps to a.compareTo(b) > 0
a >= b maps to a.compareTo(b) >= 0
a < b maps to a.compareTo(b) < 0
a <= b maps to a.compareTo(b) <= 0
Other Operators
a + b maps to a.plus(b)
a - b maps to a.minus(b)
a * b maps to a.multiply(b)
a / b maps to a.divide(b)
a++ and ++a maps to a.increment(b)
a-- and --a maps to a.decrement(b)
a[b ] maps to a.get(b)
a[b ] = c maps to a.put(b, c)

Groovy Closures
Closure可以看成function,或是說程式的片段。他會被編譯成繼承於groovy.lang.Closure。
這個Class會有call這個method,透過它可以呼叫這個closure。closure用以下這種方法定義
{ comma-separated-parameter-list | statements }
例子
1
2
3
    closure = { bill, tipPercentage | bill * tipPercentage / 100 }
    tip = closure.call(25.19, 15)
    tip = closure(25.19, 15) // equivalent to previous line

而只有一個參數的closure可以用it這個關鍵字代表唯一的參數,
以下兩個是等義的
1
2
    { x | println x }
    { println it }


Groovy Beans
以下是一個Groovy Bean的例子
1
2
3
4
    class Car {
      String make
      String model
    }


但是背後事實上會是如此
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    public class Car {
        private String make;
        private String model;
      
        public String getMake() {
            return make;
        }
      
        public String getModel() {
            return model;
        }
      
        public void setMake(String make) {
            this.make = make;
        }
      
        public void setModel(String model) {
            this.model = model;
        }
    }

Groovy Bean可以用有名參數(named parameter)的方式產生
1
    myCar = new Car(make:'Toyota', model:'Camry')



Groovy Lists
Groovy list是java.util.ArrayList的物件,以下是使用List的例子
1
2
3
4
5
6
7
8
9
10
11
    cars = [new Car(make:'Honda', model:'Odyssey'),
            new Car(make:'Toyota', model:'Camry')]
 
    println cars[1] // refers to Camry
 
    for (car in cars) { println car } // invokes Car toString method
 
    class Car {
      make; model
      String toString() { "Car: make=${make}, model=${model}" }
    }

Empty List可以直接用[]
1
    cars = []

一個物件可以用兩種方式新增
1
2
    cars.add car
    cars << car        

count
1
    [1, 2, 3, 1].count(1) 會回傳2

immutable
1
2
      list = [1, 2, 3].immutable()
      list.add 4 // throws java.lang.UnsupportedOperationException

intersect
1
    [1, 2, 3, 4].intersect([2, 4, 6]) returns [2, 4].           

join
1
    ['one', 'two', 'three'].join('^') 會回傳 "one^two^three".     

sort
排序可以接受用java.util.Compartor或是Closure
1
2
3
4
5
6
7
    fruits = ['kiwi', 'strawberry', 'grape', 'banana']
    // The next line returns [banana, grape, kiwi, strawberry].
    sortedFruits = fruits.sort()
    
    // The next line returns [kiwi, grape, banana, strawberry].
    sortedFruits =
      fruits.sort {l, r | return l.length() <=> r.length()}        

min/max
1
2
    [5, 9, 1, 6].min() 回傳 1
    [5, 9, 1, 6].max() 回傳 9

reverse
1
    [1, 2, 3].reverse() 回傳 [3, 2, 1] 

plus
1
    [1, 2, 3] + [2, 3, 4] 回傳 [1, 2, 3, 2, 3, 4]    

minus
1
    [1, 2, 3, 4] - [2, 4, 6] 回傳 [1, 3] 


Groovy Maps
Groovy Maps是java.util.HashMap的物件,以下是使用Map的例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    players = ['baseball':'Albert Pujols',
               'golf':'Tiger Woods']
 
    println players['golf'] // prints Tiger Woods
    println players.golf // prints Tiger Woods
 
    for (player in players) {
      println "${player.value} plays ${player.key}"
    }
 
    // This has the same result as the previous loop.
    players.each {player |
      println "${player.value} plays ${player.key}"
    }

空的Map可以用[:]代表
1
    players = [:]   


Groovy Ranges
Range是由".."或是"..."產生
定義如下
3..7 產生一個range從 3 到 7
3...7 產生一個range從 3 到 6
"A".."D" 產生一個range從 "A" 到 "D"
"A"..."D" 產生一個range從 "A" 到 "C"

Groovy Switch
Groovy中Switch支援個種物件,包括Class、List、Range、Pattern。
case是透過isCase這個method來做判斷。而很groovy提供許多overrloaded的isCase。
除非overloaded特別的型態,isCase是用equals此method。如果case後面是
接一個class,則使用instanceof此operator。而isCase也可以在我們所定義
的class中override掉。
以下是各種type的例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    switch (x) {
      case 'Mark':
        println "got my name"
        break
      case 3..7:
        println 'got a number in the range 3 to 7 inclusive'
        break
      case ['Moe', 'Larry', 'Curly']:
        println 'got a Stooge name'
        break
      case java.util.Date:
        println 'got a Date object'
        break
      case ~"\\d{5}":
        println 'got a zip code'
        break
      default:
        println "got unexpected value ${x}"
    }


Groovy Looping
有提供六種loop
for
1
    for (i in 1..1000) { println i }

while
1
2
    i = 1
    while (i <= 1000) { println i; i++ }

each
1
    (1..1000).each { println it }

times
1
2
    1000.times { println it }
    // values go from 0 to 999

upto
1
    1.upto(1000) { println it } 

step
1
2
3
    1.step(1001, 1) { println it }
    // values go from 1 to 1000;
    // stopping one before the parameter value


List/Map/String Methods That Accept a Closure
List Map String都支援Closure當作參數
each
它會把collection中的每一個元素或是String的每一個字元都跑一遍。
並且都丟入closure執行。如下
1
    [5, 9, 1, 6].each {x | println x} 

或是
1
    [5, 9, 1, 6].each {println it} 

collect
它會把collection或string轉成另一個新的。下面是把每個都乘二的例子。
1
    doubles = [5, 9, 1, 6].collect {x | x * 2} //回傳[10, 18, 2, 12]


find
取得collection中第一個符合closure中的元素。
1
    [5, 9, 1, 6].find {x | x > 5} //回傳9


findAll
1
    [5, 9, 1, 6].findAll {x | x > 5} // 回傳[9, 6]


every
回傳是否所有的collection的item都符合closure的條件。
1
    [5, 9, 1, 6].every {x | x < 7} // 回傳false


any
回傳是否有任何collection的item符合closure的條件。
1
    [5, 9, 1, 6].any {x | x < 7} //回傳true


inject
傳進一個value到第一輪的closure中,而之後都把前一輪的結果
丟進下一輪中。以下是一個比較奇怪的方式算費式函數(factorial)
1
2
3
    factorial = [2, 3, 4, 5].inject(1) {
      prevResult, x | prevResult * x
    }    


File I/O
從檔案一行一行讀進來 (兩種選擇)
以下的"..."都代表省略的code
1
2
3
    file = new File('myFile.txt')
    file.eachLine { println it }
    lineList = file.readLines()

讀二進位的檔案 (兩種選擇)
1
2
3
    file = new File('myFile.txt')
    file.eachByte { println it }
    byteList = file.readBytes()

找出目錄中的所有檔
1
2
    dir = new File('directory-path')
   dir.eachFile { file | . . . }

讀入並關掉資源
此方法可以保證在讀完後會把資源關閉,即時會產生exception。
1
2
3
    file.withReader { reader | . . . }
    reader.withReader { reader | . . . }
    inputStream.withStream { is | . . . }

寫出並關掉資源
此方法可以保證在寫完後會把資源關閉,即時會產生exception。
1
2
3
4
5
    file.withWriter { writer | . . . }
    file.withPrintWriter { pw | . . . }
    file.withOutputStream { os | . . . }
    writer.withWriter { writer | . . . }
    outputStream.withStream { os | . . . }


Overloaded Left Shift Operator
連接字串(To append strings)
1
2
    s = 'foo'
    s = s << 'bar'

連接字串緩衝(To append to a StringBuffer)
1
2
    sb = new StringBuffer('foo')
    sb << 'bar'

新增到List(To add to lists)
1
2
    colors = ['red', 'green']
    colors << 'blue'

寫到串流最後(To write to the end of streams)
1
2
3
    w = new File('myFile.txt').newWriter()
    w << 'foo' << 'bar'
    w.close()


Object Navigation
用"->"來代替"."可以避免產生NullPointerException。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    class Team {
      String name
      Person coach
      players = []
    }
   
    class Person {
      String name
    }
 
    p = new Person(name:'Mike Martz')
    t = new Team(name:'Rams', coach:p)
 
    // The next line prints the same as team.getCoach().getName().
    println "coach = ${t.coach.name}"
 
    t = new Team(name:'Blues')
 
    // The next line returns null,
    // it doesn't throw NullPointerException.
    println "coach = ${t->coach->name}"
 
    // The next line throws NullPointerException.
    println "coach = ${t.coach.name}"


Groovy Reflection
印出所有GString中的methods
1
GString.class.methods.each { it.name }


Catching Unimplemented Methods
類別可以去捕捉所有沒有實作的類別,例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    o = new CatchCall()
 
    // 這行會印出 "unknown method Mark called with [19]".
    println o.foo("Mark", 19)
 
    class CatchCall {
      invokeMethod(String name, Object args) {
        try {
          return metaClass.invokeMethod(this, name, args)
        } catch (MissingMethodException e) {
          // Can insert logic here to deal with certain
          // method names and arguments in special ways.
          return "unknown method ${name} called with ${args}"
        }
      }
    }


Groovy Markup
Groovy Markup使用了剛提到的invokeMethod這個method去把所有沒定義
的method轉換成"nodes". 傳進的參數會被視為nodes的屬性。而method後的
closure會被視為nodes的內容。有非常多的使用方式如,

1. 建造簡單的Data Structure tree. (NodeBuilder)
2. 建造Dom Tree. (DomBuilder)
3. 產生SAX Event. (SaxBuiulder)
4. 產生HTML或XML (MakeupBuilder)
5. 執行AntTask (AntBuilder)
6. 產生Swing的GUI (SwingBuilder)

除此之外,也可以透過繼承BuilderSupport去客製化自己的builder。

Generating HTML
以下是透過MarkupBuilder產生HTML的範例n
1
2
3
4
5
6
7
8
9
10
11
12
    import groovy.xml.MarkupBuilder
 
    mb = new MarkupBuilder()
    mb.html() {
      head() {
        title("This is my title.")
      }
      body() {
        p("This is my paragraph.")
      }
    }
    println mb


產生的HTML
1
2
3
4
5
6
7
8
    <html>
      <head>
        <title>This is my title.</title>
      </head>
      <body>
        <p>This is my paragraph.</p>
      </body>
    </html>


Generating XML
以下是透過MarkupBuilder產生XML的範例n
1
2
3
4
5
6
7
8
9
10
    import groovy.xml.MarkupBuilder;
 
    mb = new MarkupBuilder()        
    mb.autos() {
      auto(year:2001, color:'blue') {
        make('Toyota')
        model('Camry')
      }
    }
    println mb

產生的XML
1
2
3
4
5
6
    <autos>
      <auto year='2001' color='blue'>
        <make>Toyota</make>
        <model>Camry</model>
      </auto>
    </autos>


Groovy SQL
Groovy讓使用SQL更容易,以下是範例n
1
2
3
4
5
6
7
8
    import groovy.sql.Sql
 
    dbURL = 'jdbc:odbc:MusicCollection'
    jdbcDriver = 'sun.jdbc.odbc.JdbcOdbcDriver'
    sql = Sql.newInstance(dbURL, jdbcDriver)
    sql.eachRow('select * from Artists') {
      println it.Name
    }


Groovlets
Groovlet可以拿來取代Servlet或JSP,他提供以下幾種隱性變數。
1. out - 等同HttpServletResponse.getWriter()
2. request - the HttpServletRequest
3. session - the HttpSession

它使用"Here Doc"的方式來產生文件
1
2
3
4
5
6
7
8
9
10
11
    out.println <<<EOS
    <html>
      <head>
        <title>My Simple Groovlet</title>
      </head>
      <body>
        <h1>My Simple Groovlet</h1>
        <p>Today is ${new java.util.Date()}.</p>
      </body>
    </html>
    EOS

GroovyServlet會編譯Groovlets並且快取(cache)住,直到內容改變。
以下是一個web.xml去註冊GroovyServlet的範例n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <?xml version="1.0"?>
    <!DOCTYPE web-app
      PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
      "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
      <servlet>
        <servlet-name>Groovy</servlet-name>
        <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>Groovy</servlet-name>
        <url-pattern>*.groovy</url-pattern>
      </servlet-mapping>
    </web-app>


popcorny edited on 2004-03-24 21:02
reply to postreply to post
作者 Re:Groovy Language簡介 [Re:popcorny]
Biologic

生物學下的產物



發文: 524
積分: 4
於 2004-03-24 10:45 user profilesend a private message to usersend email to Biologicreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
有一些文法跟 OCL 中的數學式 很像....

我看以後大家要用數學式寫程式了


reply to postreply to post
作者 Re:Groovy Language簡介 [Re:popcorny]
T55555

Java, Ruby, Haskell

版主

發文: 1026
積分: 24
於 2004-03-24 23:57 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
覺得抄了不少 Ruby, Smalltalk ...
(唉, 又沒有 Ruby, Smalltalk 的 "pure" Oriented-Object 的精神, 也沒有 Ruby 的精簡... 如果不是為了 Java Standard API package, 我只會選擇 Ruby )


T55555 edited on 2004-03-25 00:01
reply to postreply to post
作者 Re:Groovy Language簡介 [Re:T55555]
Duncan

還隱隱作痛

版主

發文: 7816
積分: 39
於 2004-03-25 11:20 user profilesend a private message to usersend email to Duncanreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
T55555 wrote:
覺得抄了不少 Ruby, Smalltalk ...
(唉, 又沒有 Ruby, Smalltalk 的 "pure" Oriented-Object 的精神, 也沒有 Ruby 的精簡... 如果不是為了 Java Standard API package, 我只會選擇 Ruby )


也抄了不少 Python,語法也沒有 Python 精簡Big Smile。和 Jython 比較起來,Groove 連 Java core classes 的使用這項優勢都沒有。但我還是要玩玩看,我想其和 Java AP 的整合會較容易。


reply to postreply to post

給我
辣味豆腐 其餘免談
作者 Re:Groovy Language簡介 [Re:popcorny]
popcorny

Jakarta 2%

版主

發文: 752
積分: 20
於 2004-03-25 13:54 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
那這麼問好了
請問Ruby跟Python哪些功能是最想加到Groovy中的?
因為我Ruby沒玩過.. Python只玩過一點點..所以請教一下大家 Big Smile


reply to postreply to post
作者 Re:Groovy Language簡介 [Re:popcorny]
T55555

Java, Ruby, Haskell

版主

發文: 1026
積分: 24
於 2004-03-25 22:07 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
popcorny wrote:
那這麼問好了
請問Ruby跟Python哪些功能是最想加到Groovy中的?
因為我Ruby沒玩過.. Python只玩過一點點..所以請教一下大家 Big Smile


有些是語言文法的不同, 想加也加不了... (即使有可能, 也會變的非常 complexe)

For Example:
(1) Everything in Ruby are objects, no exception. (no primitive type)
Java try do it by auto-boxing. ( to wrap all primitive types to object .... )
In Ruby, you can write -1.abs ( absolute method of -1 object )
just like you do in java ( "String".length() ) ==> "..." define String object
In Ruby even a number literal, it becomes a Fixnum object.

(2) Ruby allows you modify an instance object at run-time.
This is impossible on Java. In Java you must create a "class", and all new
instance object of that class are all the "same".
You cannot do something like " instance object obj1 of class A has method
abc(); and instance object obj2 of the same class A has no method abc()"
==> it is impossible in Java, but in Ruby almost everything can run-time dynamically change ....
(This seems useless and complexe, but see some Ruby example codes, you will find out it is very useful and powerful ... )

(3) Object can only have access methods, no variable allow outside to touche. ( touche inside variable by its access methods; it is extreme opposite of JavaScript, which everything are variables, even a method (callback fucntion) is variable (like C/C++ function pointer) )
The way Ruby did, it allows you to write something like:
[1,2,3].sort.revser.each {|e| p e}
chain as many methods as you want without the need parentheses and no any confusion.

[ take this out: (4) Mixin feature, it is now in Groovy ]

....etc.
too many stuffs to list.

(Each language has its own strength, you may copy its "syntax", but
the "grammar" sometime is impossible to copy ... )


T55555 edited on 2004-03-26 02:22
reply to postreply to post
作者 Re:Groovy Language簡介 [Re:T55555]
Duncan

還隱隱作痛

版主

發文: 7816
積分: 39
於 2004-03-26 00:28 user profilesend a private message to usersend email to Duncanreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
T55555 wrote:
(2) Ruby allows you modify an instance object at run-time.
This is impossible on Java. In Java you must create a "class", and all new
instance object of that class are all the "same".
You cannot do something like " instance object obj1 of class A has method
abc(); and instance object obj2 of the same class A has no method abc()"
==> it is impossible in Java, but in Ruby almost everything can run-time dynamically change ....
(This seems useless and complexe, but see some Ruby example codes, you will find out it is very useful and powerful ... )

(3) Object can only have access methods, no variable allow outside to touche. ( touche inside variable by its access methods; it is extreme opposite of JavaScript, which everything are variables, even a method (callback fucntion) is variable (like C/C++ function pointer) )
The way Ruby did, it allows you to write something like:
[1,2,3].sort.revser.each {|e| p e}
chain as many methods as you want without the need parentheses and no any confusion.


我想請教一下,Ruby 要怎麼動態抽換 instance method?(怎麼寫)
我稍微看一下 Ruby 的語法還沒弄清楚要怎麼透過 access method 來更換 instance method 的實做。


reply to postreply to post

給我
辣味豆腐 其餘免談
作者 Re:Groovy Language簡介 [Re:Duncan]
T55555

Java, Ruby, Haskell

版主

發文: 1026
積分: 24
於 2004-03-26 00:56 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
Duncan wrote:
我想請教一下,Ruby 要怎麼動態抽換 instance method?(怎麼寫)
我稍微看一下 Ruby 的語法還沒弄清楚要怎麼透過 access method 來更換 instance method 的實做。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
The article show you a litte bit about Ruby's power ...
At the end of http://www.rubycentral.com/book/ospace.html
It said:
Compile Time? Runtime? Anytime!
 
The important thing to remember about Ruby is that 
there isn't a big difference between ``compile time'' and ``runtime.'' 
It's all the same. You can add code to a running process. 
You can redefine methods on the fly, change their scope from public to private, and so on. 
You can even alter basic types, such as Class and Object. 
 
Once you get used to this flexibility, it is hard to go back to a static language such as C++, 
or even to a half-static language such as Java. 
 
But then, why would you want to? 


OK, 廢話少說, In Ruby, it is called "Singleton Method", here is a simple example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyClass
  def size
    print "25\n"
  end
end
 
t1 = MyClass.new  ## t1 is instance object of MyClass
t2 = MyClass.new  ## t2 is instance object of MyClass
 
## redefine instance method on the fly ...
def t2.size
  print "T55555\n"
end
 
t1.size  ## print 25
t2.size  ## piint T55555


Ruby has a lot of features, if you are interesting about Ruby,
maybe open other thread instead of discuss on Groovy Thread.


T55555 edited on 2004-03-26 01:10
reply to postreply to post
作者 Re:Groovy Language簡介 [Re:T55555]
tempo



版主

發文: 645
積分: 7
於 2004-03-26 01:55 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
T55555 wrote:
(4) Mixin feature ...

這個看來好像有或是在支援的計劃內:
http://wiki.codehaus.org/groovy/MixinSupport


reply to postreply to post
Welcome to: gamelet.com
and my blog: www.pocketshark.com/blog/page/tempo
» JWorld@TW »  Languages on JVM » Groovy

reply to topicthreaded modego to previous topicgo to next topic
  已讀文章
  新的文章
  被刪除的文章
Jump to the top of page

JWorld@TW 本站商標資訊

Powered by Powerful JuteForum® Version Jute 1.5.8