重载一时爽,一直重载一直爽。

最近在读《Groovy in action》一本书重新复习了Groovy的一些语法特性,迷恋上这个重载操作符的功能,爽的不要要的。分享一个Demo。

由于Groovy语法跟Java差别略大但又基本完全兼容Java语法,这个Demo依然以Java语法写出来,方便大家理解。

package com.FunTester.demo

import com.fun.frame.SourceCode

class demo1 extends SourceCode {

public static void main(String[] args) {
def s = "fun" * 3 << "fan"

println s

Demo demo = new Demo()
Demo a = new Demo()

Demo demo1 = demo + a

Demo sssss = demo + 3

Demo fsa = demo * 3

Demo demo2 = demo / 9

Demo demo3 = demo << a

Demo demo4 = demo >> a

Demo demo5 = demo++


def i = 2 >>> 1

}

staticclass Demo {

def plus(Demo demo) {
output("加法对象")
this
}

def plus(int s) {
output("加法")
this
}

def multiply(int a) {
output("乘法")
this
}

def div(int a) {
output("除法")
this
}

def leftShift(Demo demo) {
output("<<操作")
this
}

def rightShift(Demo demo) {
output(">>操作")
this
}

def next() {
output("++操作")
this
}
}
}

控制台输出

Groovy重载操作符_测试框架

惊不惊喜意不意外!

下面结合性能测试框架的thread类写一个:

RequestThreadTimes requestThreadTimes = new RequestThreadTimes(FanLibrary.getHttpGet(""), 100);
List<RequestThreadTimes> threads = requestThreadTimes * 100;
new Concurrent(threads).start()

乘法重载如下:

  /**
* 乘法
*
* @param i
* @return
*/
public List<RequestThreadTimes> multiply(int i) {
ArrayList<RequestThreadTimes> threads = new ArrayList<>(i);
i.times {
threads << this.clone();
}
threads
}

哈,哈,哈!

  • 还有一个大秘密:Groovy连操作符“.”也能重写。


Groovy重载操作符_java_02