Groovy Discovery: Writing groovy-style code for strings

Source: Internet
Author: User

This article is used to describe some of the groovy-style code in the handling of strings, and the groovy-style code here is mostly different from the coding style of the Java language.

First, we're going to define a string object to use as our example:

def str = "hello"

Now, what we're going to say is the style of the substring.

In the Java language, to remove a substring labeled 1 and 2, you must use the "substring" method as shown here:

println str.substring(1,3)

And in the groovy language, we just have to encode the following:

println str[1..2]

The results of the run are:

el

Next, we want to get the substring starting with subscript 1, to the penultimate digit, in the Java language, we must encode the following:

println str.substring(1,str.length()-1)

However, the groovy language-style code is the following:

println str[1..-2]

The results of the operation are:

ell

The above coding style will be the basis of our handling of strings in the groovy language. The following coding style code starts here.

Now, we're going to simulate that in the Java language, when we use reflection technology, we often need to get the "set" and "got" methods of the property from an attribute name of the known JavaBean:

def propName = "email"

def firstSetFunctionName = "set"+propName.substring(0,1).toUpperCase()

def nextSetFunctionName = propName.substring(1,propName.length())

def setFunctionName = firstSetFunctionName+nextSetFunctionName

def firstGetFunctionName = "get"+propName.substring(0,1).toUpperCase()

def nextGetFunctionName = propName.substring(1,propName.length())

def getFunctionName = firstGetFunctionName+nextGetFunctionName

println setFunctionName

println getFunctionName

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.