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
}