15分でわかるGroovy-概要

Groovyは、Python、Ruby、およびSmalltalkの機能を備えたJava言語の代替として、Javaプラットフォーム用に開発されたオブジェクト指向プログラミング言語です。



Groovyは、バイトコードのJVM動的コンパイルでJavaのような構文を使用し、他のJavaコードおよびライブラリーと直接連携します。 この言語は、任意のJavaプロジェクトで、またはスクリプト言語として使用できます。



Groovyの機能(Javaとの区別):



-静的および動的タイピング

-リスト、連想配列、配列、正規表現の組み込み構文

-短絡

-オーバーロード操作



[ http://ru.wikipedia.org/wiki/Groovy ]



さらに、ほとんどの場合、Javaコードは有効なgroovyコードです。





設置



インストールするには、からアーカイブをダウンロードする必要があります site 、それを便利な場所に解凍し、環境変数GROOVY_HOMEを追加し、PATHでgroovy / binにパスを追加します。

export GROOVY_HOME=~/path/to/groovy/ export PATH=$GROOVY_HOME/bin:$PATH
      
      







NetBeans IDE 7.0では、groovyサポートがすぐに使用できます。EclipseIDEには、 ここから入手できる非常に優れたプラグインがあります。



グルーヴィー



javaとの最も重要な違い:Groovyでは、すべてがオブジェクトです。 すべてのプリミティブ型はすぐにオブジェクトにパックされます。 つまり 「Int x」は実際には「整数x」です



 println 1.class int a = 10 println a.class
      
      







 class java.lang.Integer class java.lang.Integer
      
      







すべてのパッケージタイプが不変であることを忘れないでください。したがって、計算を行うたびに新しいオブジェクトが作成されます。



Groovyの行



1)Java文字列-単一引用符で囲まれた文字列

2)Groovy Strings、別名GStrings-通常の引用符

グルーヴィーな文字列にパラメーターを挿入できますが、通常の文字列にはパラメーターを挿入できません



 javaString = 'java' groovyString = "${javaString}" j = '${javaString}' bigGroovyString = """ ${javaString} ${groovyString} ${j} ${2 + 2} """ println bigGroovyString
      
      





  java java ${javaString} 4
      
      







+および*操作は文字列に適用可能

 groovy:000> a = "a" ===> a groovy:000> a + "123" ===> a123 groovy:000> a * 5 ===> aaaaa
      
      







また、++および--文字列に適用します(groovyは演算子のオーバーロードをサポートしているため)

 groovy:000> a = 'abc' ===> abc groovy:000> a++ ===> abd groovy:000> a-- ===> ab
      
      







Groovyには、言語構成のレベルで一連の正規表現があります。

 groovy:000> r =~ '^a$' ===> java.util.regex.Matcher[pattern=^a$ region=0,1 lastmatch=]
      
      







マップ+リストのネイティブサポート



辞書(マップ)およびリストも、言語構成のレベルでサポートされています。

 groovy:000> a = [1, 3, 5] ===> [1, 3, 5] groovy:000> b = [1: true, 0: false] ===> {1=true, 0=false}
      
      







範囲



次のように、groovyのリストアイテムにアクセスできます。

 groovy:000> a = "0123456789" ===> 0123456789 groovy:000> a[1..4] ===> 1234 groovy:000> a[1..-1] ===> 123456789 groovy:000> a[-1..0] ===> 9876543210 groovy:000> a[1..<9] ===> 12345678 groovy:000> a[1, 3, 5] ===> 135 groovy:000> b = 1..5 ===> 1..5 groovy:000> a[b] ===> 12345
      
      







範囲は同じオブジェクトなので、後者のような構成が可能です。 pythonのような負のインデックスは、リストの最後から要素を返します。



範囲は次の行で構成できます。

 groovy:000> 'a'..'aa' ===> a..aa
      
      







さらに、next()およびprev()メソッドを持つオブジェクトから範囲を作成できます。



サイクル



groovyのループはjavaのループとまったく同じですが、さらにもう1つの「foreach」が追加されています。

 for (i in 0..9) { print i } for (int i = 0; i < 9; ++i) { print i } for (Integer i : 0..9) { print i }
      
      







機能



 def functionA(argA) { print ArgA } int functionB(int argB) { print argB return argB } String fuctionC() { "Hello World" }
      
      







returnキーワードはオプションであり、デフォルトでは、関数で最後に言及された変数の値が返されます。



閉鎖



クロージャーは匿名関数です。

 def cl = {a, b -> println a println b } cl(1, 2)
      
      







多くのオブジェクトには、クロージャーがパラメーターとして渡されるメソッドがあります。

 1.upto 10, { print it } 10.times { print it }
      
      







クロージャーを適用できるシーケンスを処理するための多数のメソッドが利用可能です。



 'qwerty'.each { print it } ('a'..'z').each { print it } ('a'..'z').findAll { el -> // = filter el in ['e', 'y', 'u', 'i', 'o', 'a'] }.each { print it + ' ' } (0..10).collect { el -> // = map el * 10 }.each { print it + ' ' } def sum = (0..10).inject(0) { prev, elem -> // = reduce return prev + elem }
      
      







また、クロージャーでreturnキーワードを使用する必要もありません。 パラメータ名が明示的に指定されていない場合、デフォルトで使用されます。



クロージャはオブジェクトなので、他のクロージャからそれを返すことを妨げるものは何もないので、高階関数を作成します。

 def cloA = {param -> def cloB = { return param * 10 } } def b = cloA(10) println b(10)
      
      







ファイル





ディレクトリには、eachFile関数とeachFileRecursive関数があります。



 new File('.').eachFile { println it }
      
      





 ./.project ./src ./.settings ./.classpath ./bin
      
      







テキストファイルを処理するには-eachLine関数:

 new File('textfile.txt').eachLine { println it }
      
      







ファイルへの書き込みも非常に便利です。

 def pw = new File('textfile.txt').newPrintWriter() pw.println("new line")
      
      







クラス



 class Account { String name BigDecimal value } //      //   -    // a = new Account() // a.setName("Account #1") // a.setValue(new BigDecimal(10)) a = new Account(name : "Account #1", value : new BigDecimal(10)) //      def name = a.getName() a.setName("Account #2") println "${a.name}" class Person { def first def last //    void setFirst(first) { println "${this.first} is becoming ${first}" this.first = first } } p = new Person(first : "A", last : "G") //    ,     p.first = "C" println "${p.first} ${p.last}" //    java class ExtendedAccount extends Account { def debt //   ExtendedAccount(name, value, debt) { setName(name) setValue(value) setDebt(debt) } def String toString() { "${name} ${value} ${debt}" } } //    "Could not find matching constructor for: ExtendedAccount()" //e = new ExtendedAccount() println new ExtendedAccount("A", new BigDecimal(10), 1)
      
      







不変クラスは、不変アノテーションを使用して定義されます。



 @Immutable class ImmutableClass { String a Integer b } def ic = new ImmutableClass(a : "a", b : 1)
      
      







この注釈を使用する場合、フィールドがどのタイプのデータであるかを明示的に示す必要があります。



オペレーター





「?:」エルビス演算子

 def b = a ?: "b"
      
      





変数aをチェックし、nullまたはfalseの場合、次に示す値を使用します。 それ以外の場合、変数aの値が取得されます。



「?。」 安全なナビゲーション

NullPointerExceptionエラーを回避するために使用されます

 def user = Users.get("a") def posts = user?.posts println posts
      
      





ユーザーがNullPointerExceptionをスローする代わりにnullを含む場合、nullを返します。



「*。」 スプレッド演算子

指定したメソッドをコレクションのすべての要素に適用します。 以下と同等:

 parent*.action == parent.collect {ch -> child?.action}
      
      







使用例:

 def sizes = ['string', 'long string']*.size() println sizes
      
      





 [6, 11]
      
      







monjoを使用してリストと辞書をコンパイルすることもできます。

 def x = [2, 3] def y = [0, 1, *x, 4] println y def a = [3 : 'c', 4 : 'd'] def b = [1 : 'a', 2: 'b', * : a, 5 : 'e'] println b
      
      





 [0, 1, 2, 3, 4] [1:a, 2:b, 3:c, 4:d, 5:e]
      
      







Groovyでは、演算子+、-、*などをオーバーロードできます。 これを行うには、クラスに適切なメソッドを定義する必要があります。 たとえば、++演算子をオーバーロードするには、next()メソッドをオーバーライドする必要があります。



 class RandomVal { //          private def value private Random randomGen = new Random() def next() { this.value = randomGen.nextInt() } RandomVal() { this.value = randomGen.nextInt() } def String toString() { "${this.value}" } } def r = new RandomVal() println(r) r++ println(r)
      
      







演算子「==」はすべてのオブジェクトに対してすでにオーバーロードされており、「isEquals()」メソッドを呼び出します。 演算子をオーバーロードするために再定義する必要があるメソッドの完全なリストは、 http//groovy.codehaus.org/Operator+Overloadingで入手できます



SQL





SQLクエリは非常に簡単に処理されます。

 import groovy.sql.Sql def final ADDRESS = "jdbc:jtds:sqlserver://serverName/dbName" def final USERNAME = "username" def final PASSWD = "password" def final DRIVER = "net.sourceforge.jtds.jdbc.Driver" sql = Sql.newInstance(ADDRESS, USERNAME, PASSWD, DRIVER) sql.eachRow("select * from tableName") { el -> println "${el.id} -- ${el.firstName}" } def firstName = "A" def lastName = "G" sql.execute("insert into tableName (firstName, lastName) " + "values (${firstName}, ${lastName})") sql.execute("insert into tableName (firstName, lastName) " + "values (?, ?)", [firstName, lastName])
      
      







XML



groovyには、XMLの生成に使用できるビルダーがあります。 生成のために、MarkupBuilderオブジェクトのインスタンスが作成され、そのインスタンスで擬似メソッドが呼び出されます。このメソッドの名前と渡されたパラメーターは、タグの生成に使用されます。



 import groovy.xml.MarkupBuilder def mb = new MarkupBuilder() mb.html() { head() { title("This is the title") } body() { div("class" : "main") { p("this is the body") } } }
      
      





結論:

 <html> <head> <title>This is the title</title> </head> <body> <div class='main'> <p>this is the body</p> </div> </body> </html>
      
      







任意のPrintWriterをパラメーターとしてMarkupBuilderコンストラクターに渡すことができます。

 def fb = new MarkupBuilder(new File("index.html").newPrintWriter())
      
      







XML解析も非常に簡単です。

 import groovy.xml.MarkupBuilder import java.io.StringWriter def sw = new StringWriter() def mb = new MarkupBuilder(sw) mb.html() { body() { div("class" : "main") { p("this is the body") } div() { p("this is the body 1") p("this is the body 2") p("this is the body 3") } } } def xml = sw.toString() println xml import groovy.util.XmlParser; def parser = new XmlParser() def doc = parser.parseText(xml) //def doc = parser.parse("index.html") println doc.body.div[1].p[1] //  Node println doc.body.div[1].p //  ,   Node println doc.body.div["@class"] //    class   div
      
      







結論:

 <html> <body> <div class='main'> <p>this is the body</p> </div> <div> <p>this is the body 1</p> <p>this is the body 2</p> <p>this is the body 3</p> </div> </body> </html> p[attributes={}; value=[this is the body 2]] [p[attributes={}; value=[this is the body 1]], p[attributes={}; value=[this is the body 2]], p[attributes={}; value=[this is the body 3]]] [main, null]
      
      







グルーブレット



GroovyServletクラスを使用すると、Groovyでスクリプトをサーブレットとして実行できます。

まず、このために、web.xmlに数行を追加する必要があります。



 <servlet> <servlet-name>GroovyServlet</servlet-name> <servlet-class>groovy.servlet.GroovyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GroovyServlet</servlet-name> <url-pattern>*.groovy</url-pattern> </servlet-mapping>
      
      







.groovyファイルに対するすべてのリクエストは、GroovyServletクラスによって処理されます。

これらのスクリプトでは、次の変数がすでに使用可能です。



-リクエストとレスポンス

-コンテキスト、アプリケーション、セッション

-アウト(= response.getWriter())

-sout(= response.getOutputStream())

-html(=新しいMarkupBuilder(out))



 html.html() { body() { div("class" : "main") { p("this is the body") } div() { p("this is the body 1") p("this is the body 2") p("this is the body 3") } } }
      
      







ブラウザーに生成されたhtmlページを提供します。



使用されるソースのリスト:



Kenneth Barclay、John Savage「Groovyプログラミング:Java開発者向け入門」

http://groovy.codehaus.org/



All Articles