Groovy Tip Gpath

Source: Internet
Author: User

In the groovy language, Gpath may be one of our most common functions. Of course, we use gpath mostly for operations on Groovybean objects. In fact, in addition to manipulating Groovybean objects, Gpath is also used to manipulate XML documents. Even if it is used for the operation of the Groovybean object, we may not know the use of Gpath very detailed, so we will go into detail to say gpath.

First, Gpath is used to manipulate the properties of a class, to access the properties of an object, such as the way the object. property is accessed. For example, we have the following two groovybean:

class Address
{
   String prov
   String city
}
class Person
{
   String id
   String name
   Address addr
}

Now, we can use Gpath to manipulate them:

   def addr = new Address(prov:'Hubei',city:'Xiaogan')
    def person = new Person(id:123,name:'Wallace',addr:addr)
    println person.name
    println person.addr.city

The results of the operation are:

Wallacexiaogan

You can see that "Person.name" accesses the property "name" of the object "person", and "person.addr.city" accesses the property "addr" of "person" before accessing the property "City" of "addr". With such a way of access, the combination of this type can be accessed using Gpath, regardless of how many layers are nested.

It is noteworthy that the above nested access is not secure. Take a look at the following example:

  def person = new Person(id:123,name:'Wallace')
  println person.addr.city

Such a visit would report a null pointer error. In order to solve this null pointer error, in the Java language you usually do the following non-null judgments:

if(person!=null&&person.addr!=null)
    {
      println person.addr.city
  }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.