Groovy Groovy features three study notes

(1)GroovyBean
Groovy like a JavaBean, but omit the get and set methods to display statements, provides automatic construction method, and allows you to reference a member variable with a dot (.).
class Character
{
    private int strLength
    private int wisdom
}
def pc=new Character(strLength:10,wisdom:20)
pc.strLength=30
println "STRLENGTH=["+pc.strLength+"] WISDOM=["+pc.wisdom+"]"
输出为:

STRLENGTH=[30] WISDOM=[20]
  (2) Safety dereference operator
Groovy introduces security dereference operator, with a? Symbol to help you get rid of some of the routine "if the object is null" check code. When using this symbol, Groovy introduces a special null structure, which means "do nothing" and not really a reference null.
class Person
{
    private String name;
    private Integer age;
}
people=[null,new Person(name:"billLee",age:55)]
for(Person person:people)
{
   println person?.name+" age="+person?.age
}
输出:




null age=null
billLee age=55
  (3) operator Elvis
With Elvis operator (? :) can with default values ​​if / else structure and write short. Null operator without checking with Elvis Presley, do not repeat variables.
String agentStatus="Active"
String status=agentStatus?:"Inactive"
结果:
Result: Active
  (4) Enhanced string
Groovy has extended class GString a String class, it is also more flexible than in the standard Java String stronger.
GString must use double quotes definition. For developers, the greatest advantage is the use of expression can be included may be calculated at run time (with $ {}). If GString then converted to ordinary strings (such as passed println), GString the expression will be replaced by their results.
String name="bill lee";
def dist=3*9;
String str="${name} and dist = ${dist}"
Result: bill lee and dist = 27
  GString bottom is not in Java String! In particular, it should not be GString map as a key, or if they compare equal, the result is unpredictable.
(5) Function literals
Function represents a literal value can be used as block transfer, any value may be the same as the operation of the operation. Can be used as the method to pass parameters, you can assign values ​​to variables.
Traditional achieve:
class StringUtils
{
    static String sayHello(String name)
    {
        if(name=="Tom"||name=="Jerry")
        {
            "Hello Cat and Mouse "+name+"!"
        }
        else
        {
            "Hello funs "+name+" !"
        }
    }
}
println StringUtils.sayHello("Tom")
println StringUtils.sayHello("bsr1983")
输出:
Hello Cat and Mouse Tom!
Hello funs bsr1983 !
  Function literal realization
def sayHello=
{
    name->if(name=="Tom"||name=="Jerry")
     "Hello Cat and Mouse "+name+"!"
    else  
    "Hello funs "+name+" !"
}
println sayHello("Tom")
println sayHello("bsr1983")
输出与上面的传统实现一样
  (6) a set of built-in operations
each: through the collection, wherein each of the application function literals
collect: each item collected in the collection literal application function returns the result (corresponding to another language map / reduce the map function)
inject: processing set and a function literal construct return value (corresponding to other languages ​​map / reduce reduce function)
findAll:找到集合中所有与函数字面值匹配的元素
max:返回集合中的最大值
min:返回集合中的最小值
示例代码:
moviesTitle=["Seven","SnowWhite","Die Hard"]
moviesTitle.each({x->println x})
输出



Seven
SnowWhite
Die Hard
moviesTitle=["Seven","SnowWhite","Die Hard"]
moviesTitle.each({println it})
 it变量可以用在单参的函数字面值中。
(7)对正则表达式的内置支持
~:创建一个模式(创建一个编译的Java Pattern对象)
=~:创建一个匹配器(创建一个Java Matcher对象)
==~:计算字符串(相当于在Pattern上调用Java match()方法)
示例代码
def pattern=/1010/
def input="1010"
def matcher=input =~ pattern
if(input==~ pattern)
{
    input=matcher.replaceFirst("0101")
    println input
}
输出

0101
("billlee 31"=~/(\w+) (\d+)/).each{full,name,age->println "$name is $age year old"}
输出

billlee is 31 year old
  (8)简单的XML处理
Groovy有构建器的概念,用Groovy原生语法可以处理任何树型结构的数据,包括HTML、XML和JSON。
1.创建XML
def writer=new StringWriter()
def xml=new groovy.xml.MarkupBuilder(writer)
xml.person(id:2)
{
    name "billlee"
    age 31
}
println writer.toString();
输出
<person id='2'>
  <name>billlee</name>
  <age>31</age>
</person>
  2.创建Json
def builder=new groovy.json.JsonBuilder()
def root=builder.people{
person
{
    name "billlee"
    age 31
}
}
println builder.toString()
println builder.toPrettyString()
def s=new StringWriter()
builder.writeTo(s)
println s.toString()
输出:
{"people":{"person":{"name":"billlee","age":31}}}
{
    "people": {
        "person": {
            "name": "billlee",
            "age": 31
        }
    }
}
{"people":{"person":{"name":"billlee","age":31}}}
  3.解析XML
Groovy有几种解析XML输入的办法。
XMLParser:支持XML文档的GPath表达式
XMLSlurper:跟XMLParser类似,但以懒加载的方式工作
DOMCategory:用一些语法支持DOM的底层解析
示例代码:
class XmlExample{ 
static def PERSON= 
""" 
<person id='2'> 
<name>billlee</name> 
<age>31</age> 
</person> 
""" 
} 
class Person{def id;def name;def age} 
def xmlPerson=new XmlParser().parseText(XmlExample.PERSON) 
Person p=new Person(id:xmlPerson.@id, 
name:xmlPerson.name.text(), 
age:xmlPerson.age.text()) 
println "id=${p.id} name=${p.name} age=${p.age}"
输出

id=2 name=billlee age=31
注:"""是Groovy中用来定义跨行字符串的。
 
发布了250 篇原创文章 · 获赞 7 · 访问量 3万+

Guess you like

Origin blog.csdn.net/bsr1983/article/details/84694441