Chapter 7 groovy-style dynamic object-oriented

Source: Internet
Author: User
7.1 defining classes and scripts 7.1.1 defining attributes and declaring attributes of local variables and local variables must be declared before use (except for scripts ), this helps to implement scope rules and prevent programmers from misspelling by mistake.
The script allows undeclared variables. In this case, the variables are obtained from the binding attribute of the script. If no corresponding variables are found in the binding, the variables are added to the binding, binding is a data storage that transfers variables between the script caller and the script.


The default attribute range has a special meaning in groovy. When the attribute Declaration of the range modifier is not specified, groovy will generate the corresponding access method (getter method and setter method) as needed ).The type of the defined variable is optional. Type and ModifierDef must be used as the replacement. In fact, Def is used to indicate that the attribute or variable has no type (although the internal part will be declared as the object type) The specified type of reference must meet the specified type.
Reference a property or cancel a reference to the property.In addition to using obj. fieldname to reference attributes, you can also use subscript operators to reference attributes.

Rewrite subscript operator:
Object get (String name) void set (String name, Object value) 

Rewriting the get method overwrites the dot-fieldname operator. rewriting the Set Method overwrites the field assignment operator.

Statement X. Z. Y = something what is the result of the statement execution? This is equivalent to getx (). Gety (). setz (somethine ).

7.1.2 methods and parameters can usually use Java modifiers; Declaration of return types is optional; if there are no modifiers or return types, use the def keyword to fill in the blanks, when the def keyword is used, the return type of the method is considered to be no type (although there is no return type, it is equivalent to the void method). In this case, groovy defines the return type of the method as Java. lang. object, The default method access range is public.. Method assignment
package groovyInAction.sevenclass Example7_5DeclaringMethods {static void main(String[] args) {def some = new Example7_5DeclaringMethods()some.publicVoidMethod()assert 'hi' == some.publicUntypeMethod()assert 'ho' == some.publicTypeMethod()combineMethod()}void publicVoidMethod(){}def publicUntypeMethod(){return 'hi'} def publicTypeMethod(){ return 'ho' }  protected static final void combineMethod(){}}

The current type of main method ARGs is implicitly Java. lang. the explicit object declaration parameter type is optional. When the Declaration type is ignored, groovy uses the object as the type. Multiple parameters can be used in sequence and separated by commas.

Package policyinaction. sevenclass example7_6declaringparameterlists {static void main (ARGs) {assert 'untyped '= method (1) assert 'typed' = method ('whatever ') assert 'two ARGs '= method (1, 2)} static method (ARG) {return 'untyped'} static method (string Arg) {// method overload return 'typed '} static method (arg1, number arg2) {return 'two ARGs '}}

All method calls are related to the location of the method parameter, which means that each parameter has been determined based on its location in the parameter list. There are some painful disadvantages for complicated scripts: You must remember the real Parameter order, which increases the difficulty when the parameter list is too long; for non-traditional scripts, if calling methods based on different information is meaningful, You need to construct many different methods to handle these differences, which will soon become bulky and cause difficulty in maintaining the methods, this is especially difficult if many optional parameters of the same type are optional.
Note: whenever we talk about named parameters, we mean that the map key is called as a parameter in the method. From a programmer's perspective, this looks like native support for naming parameters, but this is not the case. This technique is required because JVM does not support saving parameter names in bytecode.

package groovyInAction.sevenclass Example7_7AdvancedParameterUsages {static main(args){def summer = new Summer()assert 2 == summer.sumWithDefaults(1, 1)assert 3 == summer.sumWithDefaults(1, 1,1)assert 2 == summer.sumWithList([1,1])assert 3 == summer.sumWithList([1,1,1])assert 2 == summer.sumWithOptionals(1,1)assert 3 == summer.sumWithOptionals(1,1,1)assert 2 == summer.sumNamed(a:1,b:1)assert 3 == summer.sumNamed(a:1,b:1,c:1)assert 1 == summer.sumNamed(c:1)}}class Summer{def sumWithDefaults(a, b, c=0){ //Explicit arguments and a default valuereturn a + b + c}def sumWithList(List args){ //Define arguments as a listreturn args.inject(0) {sum,i -> sum +=i}}def sumWithOptionals(a,b,Object[] optionals){//Optional arguments as an arrayreturn a + b + sumWithList(optionals.toList())}def sumNamed(Map args){//Define arguments as a map['a','b','c'].each{ args.get(it,0)}return args.a + args.b + args.c}}

Note: The second way to implement the variable length parameter list is to overwrite the groovy dispatch method invokemethod (name, Params []), which is the method provided by every yyobject object.

Advanced naming
objectReferenct.'my.method-Name'

The purpose of this feature is to turn the name of the calling method into a part of the function. This feature is usually not used directly, but other parts of groovy will use this feature.

obj."${var}"()
7.1.3 safe reference symbol (?.)
package groovyInAction.sevenclass Example7_8ProtectingFromNullPointerExceptionsUsingTheOperator {static main(args){def map = [a:[b:[c:1]]]assert map.a.b.c == 1if(map && map.a && map.a.x){//protect with if:short-circuit evaluationassert map.a.x.c == null}try{//Protect with try/catchassert map.a.x.c == null}catch(NullPointerException npe){}assert map?.a?.x?.c == null //Safe dereferencing}}
7.1.4 Constructor (constructor)

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.