【Groovy】字符串 ( 字符串注入函数 |
您所在的位置:网站首页 › groovy调用python › 【Groovy】字符串 ( 字符串注入函数 |
文章目录一、字符串注入函数1、字符串转布尔值 asBoolean 函数2、执行字符串对应命令 execute 函数3、字符串减法 minus 函数二、完整代码示例一、字符串注入函数 Groovy 为 字符串 类 , 注入了一系列的方法 , 下面介绍几个重要的注入方法 ; 为 Groovy 字符串扩展的函数 , 都定义在 public class StringGroovyMethods extends DefaultGroovyMethodsSupport类中 ; 1、字符串转布尔值 asBoolean 函数将字符串转为布尔值函数 : 字符串长度为 0 , 则返回 false ;字符串长度大于 0 , 返回 true ;"".asBoolean();注入的 asBoolean 函数 : public class StringGroovyMethods extends DefaultGroovyMethodsSupport { /** * 将字符串(CharSequence的实例)强制为布尔值。 * 如果字符串的长度为0,则该字符串强制为false, * 反之亦然。 * * @param 字符串指定字符序列 * @返回布尔值 * @从1.7开始。0 */ public static boolean asBoolean(CharSequence string) { return string.length() > 0; } }执行如下代码 : class Test { static void main(args) { println "".asBoolean(); } }执行结果 : false2、执行字符串对应命令 execute 函数调用字符串的 execute() 方法 , 可以执行该 字符串命令 , 前提是该字符串必须是系统命令 , 不能是任意字符串 ; 注入 execute() 函数 : public class StringGroovyMethods extends DefaultGroovyMethodsSupport { /** * 将self指定的命令作为命令行进程执行。 *对于过程构造的更多控制,您可以使用 * java。lang.ProcessBuilder。 * * @param self 命令行字符串 * @返回此命令行表示刚刚启动的进程 * @在发生IOException时抛出IOException。 * @自1.0以来 */ public static Process execute(final String self) throws IOException { return Runtime.getRuntime().exec(self); } } 执行如下代码 : class Test { static void main(args) { println "cmd /c groovy -v".execute().text } }执行结果 : Groovy Version: 3.0.9 JVM: 1.8.0_91 Vendor: Oracle Corporation OS: Windows 103、字符串减法 minus 函数两个字符串之间进行减法操作 , 相当于从大的字符串中 , 删除被减去的小的字符串 ; 注入 minus() 函数 : public class StringGroovyMethods extends DefaultGroovyMethodsSupport { /** * 移除字符串的一部分。这将替换第一个事件 * 目标。将self中的toString()与“”匹配,并返回结果。 * * @param self 字符串 * @param target 表示要移除的零件的对象 * @返回一个字符串减去要删除的部分 * @自1.0以来 */ public static String minus(String self, Object target) { String text = DefaultGroovyMethods.toString(target); int index = self.indexOf(text); if (index == -1) return self; int end = index + text.length(); if (self.length() > end) { return self.substring(0, index) + self.substring(end); } return self.substring(0, index); } }代码示例 : class Test { static void main(args) { println "HelloWorld" - "World" } }执行结果 : Hello二、完整代码示例完整代码示例 : class Test { static void main(args) { println "".asBoolean(); println "cmd /c groovy -v".execute().text println "HelloWorld" - "World" } }执行结果 : false Groovy Version: 3.0.9 JVM: 1.8.0_91 Vendor: Oracle Corporation OS: Windows 10 Hello |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |