the differences between groovy and java

工业互联网工控安全与工业质检AI大模型建设方案.pptx 立即下载

Groovy tries to be as natural as possible for Java developers. We’ve tried to follow the principle of least surprise when designing Groovy, particularly for developers learning Groovy who’ve come from a Java background.

Here we list all the major differences between Java and Groovy.

1. Default imports

All these packages and classes are imported by default, i.e. you do not have to use an explicit import statement to use them:

  • java.io.*

  • java.lang.*

  • java.math.BigDecimal

  • java.math.BigInteger

  • java.net.*

  • java.util.*

  • groovy.lang.*

  • groovy.util.*

2. Multi-methods

In Groovy, the methods which will be invoked are chosen at runtime. This is called runtime dispatch or multi-methods. It means that the method will be chosen based on the types of the arguments at runtime. In Java, this is the opposite: methods are chosen at compile time, based on the declared types.

The following code, written as Java code, can be compiled in both Java and Groovy, but it will behave differently:

int method(String arg) {
    return 1;
}
int method(Object arg) {
    return 2;
}
Object o = "Object";
int result = method(o);

In Java, you would have:

assertEquals(2, result);

Whereas in Groovy:

assertEquals(1, result);

That is because Java will use the static information type, which is that o is declared as an Object, whereas Groovy will choose at runtime, when the method is actually called. Since it is called with a String, then the String version is called.

3. Array initializers

In Groovy, the { …​ } block is reserved for closures. That means that you cannot create array literals with this syntax:

int[] array = { 1, 2, 3}

You actually have to use:

int[] array = [1,2,3]

4. Package scope visibility

In Groovy, omitting a modifier on a field doesn’t result in a package-private field like in Java:

class Person {
    String name
}

Instead, it is used to create a property, that is to say a private field, an associated getter and an associated setter.

It is possible to create a package-private field by annotating it with @PackageScope:

class Person {
    @PackageScope String name
}

5. ARM blocks

ARM (Automatic Resource Management) block from Java 7 are not supported in Groovy. Instead, Groovy provides various methods relying on closures, which have the same effect while being more idiomatic. For example:

Path file = Paths.get("/path/to/file");
Charset charset = Charset.forName("UTF-8");
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
}

can be written like this:

new File('/path/to/file').eachLine('UTF-8') {
   println it
}

or, if you want a version closer to Java:

new File('/path/to/file').withReader('UTF-8') { reader ->
   reader.eachLine {
       println it
   }
}

6. Inner classes

The implementation of anonymous inner classes and nested classes follows the Java lead, but you should not take out the Java Language Spec and keep shaking the head about things that are different. The implementation done looks much like what we do for groovy.lang.Closure, with some benefits and some differences. Accessing private fields and methods for example can become a problem, but on the other hand local variables don’t have to be final.

6.1. Static inner classes

Here’s an example of static inner class:

class A {
    static class B {}
}

new A.B()

The usage of static inner classes is the best supported one. If you absolutely need an inner class, you should make it a static one.

6.2. Anonymous Inner Classes

import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

CountDownLatch called = new CountDownLatch(1)

Timer timer = new Timer()
timer.schedule(new TimerTask() {
    void run() {
        called.countDown()
    }
}, 0)

assert called.await(10, TimeUnit.SECONDS)

6.3. Creating Instances of Non-Static Inner Classes

In Java you can do this:

public class Y {
    public class X {}
    public X foo() {
        return new X();
    }
    public static X createX(Y y) {
        return y.new X();
    }
}

Groovy doesn’t support the y.new X() syntax. Instead, you have to write new X(y), like in the code below:

public class Y {
    public class X {}
    public X foo() {
        return new X()
    }
    public static X createX(Y y) {
        return new X(y)
    }
}
Caution though, Groovy supports calling methods with one parameter without giving an argument. The parameter will then have the value null. Basically the same rules apply to calling a constructor. There is a danger that you will write new X() instead of new X(this) for example. Since this might also be the regular way we have not yet found a good way to prevent this problem.

7. Lambdas

Java 8 supports lambdas and method references:

Runnable run = () -> System.out.println("Run");
list.forEach(System.out::println);

Java 8 lambdas can be more or less considered as anonymous inner classes. Groovy doesn’t support that syntax, but has closures instead:

Runnable run = { println 'run' }
list.each { println it } // or list.each(this.&println)

8. GStrings

As double-quoted string literals are interpreted as GString values, Groovy may fail with compile error or produce subtly different code if a class with String literal containing a dollar character is compiled with Groovy and Java compiler.

While typically, Groovy will auto-cast between GString and String if an API declares the type of a parameter, beware of Java APIs that accept an Object parameter and then check the actual type.

9. String and Character literals

Singly-quoted literals in Groovy are used for String, and double-quoted result in String or GString, depending whether there is interpolation in the literal.

assert 'c'.getClass()==String
assert "c".getClass()==String
assert "c${1}".getClass() in GString

Groovy will automatically cast a single-character String to char only when assigning to a variable of type char. When calling methods with arguments of type char we need to either cast explicitly or make sure the value has been cast in advance.

char a='a'
assert Character.digit(a, 16)==10 : 'But Groovy does boxing'
assert Character.digit((char) 'a', 16)==10

try {
  assert Character.digit('a', 16)==10
  assert false: 'Need explicit cast'
} catch(MissingMethodException e) {
}

Groovy supports two styles of casting and in the case of casting to char there are subtle differences when casting a multi-char strings. The Groovy style cast is more lenient and will take the first character, while the C-style cast will fail with exception.

// for single char strings, both are the same
assert ((char) "c").class==Character
assert ("c" as char).class==Character

// for multi char strings they are not
try {
  ((char) 'cx') == 'c'
  assert false: 'will fail - not castable'
} catch(GroovyCastException e) {
}
assert ('cx' as char) == 'c'
assert 'cx'.asType(char) == 'c'

10. Primitives and wrappers

Because Groovy uses Objects for everything, it autowraps references to primitives. Because of this, it does not follow Java’s behavior of widening taking priority over boxing. Here’s an example using int

int i
m(i)

void m(long l) {           
  println "in m(long)"
}

void m(Integer i) {        
  println "in m(Integer)"
}
This is the method that Java would call, since widening has precedence over unboxing.
This is the method Groovy actually calls, since all primitive references use their wrapper class.

11. Behaviour of ==

In Java == means equality of primitive types or identity for objects. In Groovy == translates to a.compareTo(b)==0, if they are Comparable, and a.equals(b) otherwise. To check for identity, there is is. E.g. a.is(b).

12. Conversions

Java does automatic widening and narrowing conversions.

Table 1. Java Conversions
 

Converts to

Converts from

boolean

byte

short

char

int

long

float

double

boolean

-

N

N

N

N

N

N

N

byte

N

-

Y

C

Y

Y

Y

Y

short

N

C

-

C

Y

Y

Y

Y

char

N

C

C

-

Y

Y

Y

Y

int

N

C

C

C

-

Y

T

Y

long

N

C

C

C

C

-

T

T

float

N

C

C

C

C

C

-

Y

double

N

C

C

C

C

C

C

-

* 'Y' indicates a conversion Java can make, 'C' indicates a conversion Java can make when there is an explicit cast, 'T` indicates a conversion Java can make but data is truncated, 'N' indicates a conversion Java can’t make.

Groovy expands greatly on this.

Table 2. Groovy Conversions
 

Converts to

Converts from

boolean

Boolean

byte

Byte

short

Short

char

Character

int

Integer

long

Long

BigInteger

float

Float

double

Double

BigDecimal

boolean

-

B

N

N

N

N

N

N

N

N

N

N

N

N

N

N

N

N

Boolean

B

-

N

N

N

N

N

N

N

N

N

N

N

N

N

N

N

N

byte

T

T

-

B

Y

Y

Y

D

Y

Y

Y

Y

Y

Y

Y

Y

Y

Y

Byte

T

T

B

-

Y

Y

Y

D

Y

Y

Y

Y

Y

Y

Y

Y

Y

Y

short

T

T

D

D

-

B

Y

D

Y

Y

Y

Y

Y

Y

Y

Y

Y

Y

Short

T

T

D

T

B

-

Y

D

Y

Y

Y

Y

Y

Y

Y

Y

Y

Y

char

T

T

Y

D

Y

D

-

D

Y

D

Y

D

D

Y

D

Y

D

D

Character

T

T

D

D

D

D

D

-

D

D

D

D

D

D

D

D

D

D

int

T

T

D

D

D

D

Y

D

-

B

Y

Y

Y

Y

Y

Y

Y

Y

Integer

T

T

D

D

D

D

Y

D

B

-

Y

Y

Y

Y

Y

Y

Y

Y

long

T

T

D

D

D

D

Y

D

D

D

-

B

Y

T

T

T

T

Y

Long

T

T

D

D

D

T

Y

D

D

T

B

-

Y

T

T

T

T

Y

BigInteger

T

T

D

D

D

D

D

D

D

D

D

D

-

D

D

D

D

T

float

T

T

D

D

D

D

T

D

D

D

D

D

D

-

B

Y

Y

Y

Float

T

T

D

T

D

T

T

D

D

T

D

T

D

B

-

Y

Y

Y

double

T

T

D

D

D

D

T

D

D

D

D

D

D

D

D

-

B

Y

Double

T

T

D

T

D

T

T

D

D

T

D

T

D

D

T

B

-

Y

BigDecimal

T

T

D

D

D

D

D

D

D

D

D

D

D

T

D

T

D

-

* 'Y' indicates a conversion Groovy can make, 'D' indicates a conversion Groovy can make when compiled dynamically or explicitly cast, 'T` indicates a conversion Groovy can make but data is truncated, 'B' indicates a boxing/unboxing operation, 'N' indicates a conversion Groovy can’t make.

The truncation uses Groovy Truth when converting to boolean/Boolean. Converting from a number to a character casts the Number.intvalue() to char. Groovy constructs BigInteger and BigDecimal using Number.doubleValue() when converting from a Float or Double, otherwise it constructs using toString(). Other conversions have their behavior defined by java.lang.Number.

13. Extra keywords

There are a few more keywords in Groovy than in Java. Don’t use them for variable names etc.

  • as

  • def

  • in

  • trait

通信行业CentOS 7内核网络栈优化:高并发连接下UDP/TCP性能调优与系统资源管理 内容概要:本文聚焦于CentOS 7系统在通信行业高并发场景下的性能调优实践,重点围绕内核网络栈优化展开,涵盖UDP/TCP缓冲区调整、文件句柄与连接跟踪表扩容、TIME_WAIT状态复用、软中断分布优化及tuned工具的自动化调优。通过具体配置参数和实际案例(如VoIP软交换系统)深入解析各项调优措施的设计原理与实施效果,有效解决高CPS下丢包、连接失败等问题,并展望了向云化、eBPF等动态智能调优方向的发展趋势。; 适合人群:从事通信系统运维、网络开发或Linux系统性能优化的技术人员,具备一定操作系统和网络基础知识,工作经验1年以上的中初级工程师。; 使用场景及目标:①应用于软交换、媒体网关、信令网关等高并发通信设备的系统调优;②解决UDP丢包、conntrack表满、TCP连接队列溢出等典型性能瓶颈;③提升系统在小包高频、低时延要求场景下的稳定性和吞吐能力。; 阅读建议:建议结合实际生产环境或测试平台同步验证文中配置,重点关注参数背后的物理意义(如BDP、softirq、conntrack机制),并配合ss、conntrack、dmesg等命令进行调优前后对比分析,确保安全可控地实施变更。 立即下载

相关推荐

2024 《计算机网络》实验教学指导书.doc

2024 《计算机网络》实验教学指导书.doc

java中assignments,Operators and Assignments(2)-JSP教程,Java基础

objective 2)determine the result of applying the boolean equals(object) method to objects of any combination of the classes java.lang.string java.lang.boolean and java.lang.object.the equals method ca...

weixin_31111259的博客 342

不平衡电网下自抗扰顺序模型预测PWM整流器控制仿真模型(Simulink仿真实现)

内容概要:本文围绕面向城市空中交通的多无人机路径规划问题展开研究,提出了一套融合全局规划、动态避障与局部协同调整的综合路径规划方法。研究内容涵盖基于改进RRT算法与图论的全局路径规划、基于动态风险场和动态窗口法(DWA)的模型预测控制实现动态避障,以及基于分布式协同控制的多无人机局部路径协同策略。通过Matlab平台构建仿真环境,在多种典型城市交通场景下对所提方法进行了系统性验证,结果表明该方法在路径安全性、编队稳定性与任务效率方面表现优异。文章还深入探讨了算法的创新点与未来研究方向,为复杂城市环境下多无人机系统的自主协同提供了理论支撑与技术路径。; 适合人群:具备自动化、控制理论、计算机科学或相关领域基础知识,从事无人机系统、智能交通、路径规划、多智能体协同控制等方向研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①为城市空中交通系统中的多无人机安全、高效飞行提供可靠的路径规划解决方案;②支持在复杂、动态的城市场景中开展无人机自主导航、编队飞行与协同控制的技术研究与仿真验证。; 阅读建议:建议结合提供的Matlab代码进行实践操作,重点关注算法的具体实现细节、参数配置对性能的影响以及不同仿真场景下的实验设计,以深入理解各模块的集成逻辑与实际应用效果。

Cannot use ‘<>‘ with anonymous inner classes

将Java环境由Java8改为Java9.

pxyyoona的博客 1572

XTDrone——无人机基于2D激光Lidar进行二维运动规划(细节提醒以及相关报错解决)

本文介绍了在Ubuntu 20.04系统无人机基于ROS Noetic实现HectorSLAM二维激光建图与运动规划的完整流程。主要内容包括:安装必要ROS依赖库;修改HectorSLAM的launch文件,解决坐标系转换问题;配置地图发布参数以避免覆盖已建地图;启动PX4仿真环境与XTDrone通信模块;最后通过2D导航目标点实现无人机运动规划。文中详细说明了各步骤的关键配置修改,并提供了处理常见错误(如TF转换超时)的解决方案。实现了从激光SLAM建图到路径规划的过程。

weixin_45390670的博客 993

避坑指南:ros2_control在Gazebo中的常见配置错误及解决方案

本文系统梳理了在Gazebo仿真环境中配置ros2_control框架时最常见的错误,并提供了详细的解决方案。重点解析了YAML配置文件的结构陷阱、URDF/XACRO中关键标签的正确写法、Launch文件的启动顺序管理,并分享了实用的调试命令与故障排查思路,帮助开发者高效避坑,实现流畅的关节运动控制。

q5r6s7的博客 968

Java 8 Lamda

Java 8 Lamdawe all know Lambda project is a big enhancement to the java programming language. so let’s start to learn the grammer.Backgroundjava is, an object-oriented programming language. but the lan

fly1056601582的博客 496

2025华东杯A/B/C题解题思路+可运行代码参考

这些因素包括但不限于:助滑坡的坡度、运动员的质量、滑雪板的接触面与雪地的摩擦力、空气阻力系数、运动员的体型和衣物形态等。助滑坡是运动员滑行至起跳台前的最后一段坡道,这一段坡道的坡度、长度和运动员的姿势会直接影响到起跳时的初始速度。运动员的滑行速度不仅受助滑坡的坡度影响,还受到摩擦力、空气阻力和重力等多方面因素的影响。通过合理的姿势调整,运动员能够有效减少空气阻力,增加身体的重力加速度,进而提升滑行速度。助滑坡的角度通常介于10°到12°之间,而运动员的滑行速度将受到重力、摩擦力和空气阻力的共同作用。

qq_52590045的博客 1796

Objective-C 警告相关说明

原文地址:http://nshipster.com/clang-diagnostics/

2万+

M系列芯片MacBook上UTM虚拟机部署达梦DM8的避坑指南

本文详细介绍了在M系列芯片MacBook上使用UTM虚拟机部署达梦数据库DM8的完整流程与避坑指南。针对ARM架构环境,重点解决了虚拟机选择、麒麟系统安装、系统调优及DM8命令行安装中的常见问题,为开发者提供了稳定可靠的国产数据库本地测试方案。

weixin_28455801的博客 451

【C语言】字符常量详解

字符常量是C语言中处理字符数据的重要工具。通过单引号括起一个字符,我们可以方便地使用字符常量进行字符判断、字符运算和字符串处理等操作。理解字符常量的表示方法、使用场景和ASCII码对应关系,对于编写高效的C语言程序至关重要。

LuckiBit 5017

Literal Values

Integer LiteralsInteger literals can be expressed in decimal, hexadecimal, or octal.You indicate a negative number by prefixing the literal with a – sign.For Long literals, it is necessary to append th

BrownWong的专栏 1364

深度解析:Android开发工程师(嵌入式系统方向)职位 - 技术需求、面试准备与发展路径

本文深入分析了嵌入式Android开发工程师的岗位要求和技术内涵。该职位需要掌握C/C++、Linux系统编程、硬件接口等核心技术,能够进行Android系统底层定制开发,包括HAL层实现、Framework修改、性能优化等工作。文章详细解读了岗位职责,梳理了必备技术栈,提供了针对性的面试问题与参考答案,并探讨了职业发展路径。这类岗位要求开发者兼具软件工程能力和硬件基础知识,适合在智能电视、机顶盒、车载系统等嵌入式领域发展的技术人员。

郑伟强dev的专栏 132

Differences between Java and Groovy

Differences with Java Groovy tries to be as natural as possible for Java developers. We’ve tried to follow the principle of least surprise when designing Groovy, particularly for developers l...

博客颜色 206

【微服务】Spring AI Alibaba Jmus 从部署到项目实战详解

Spring AI Alibaba Jmus 从部署到项目实战详解

congge 4184

2025年9月GESP(C++四级):排兵布阵

作为将军,你自然需要合理地排兵布阵。地图可以视为n行m列的网格,适合排兵的网格以 1 标注,不适合排兵的网格以 0 标注。现在你需要在地图上选择一个矩形区域排兵,这个矩形区域内不能包含不适合排兵的网格。请问可选择的矩形区域最多能包含多少网格?

王老师青少年编程 1377

Java Wish List: The Top Differences Between Java, Scala, Groovy, Clojure and Kotlin

A list of the top differences between Java, Scala, Groovy, Clojure and Kotlin It doesn’t matter if you’re developing in Java, Scala or any other JVM languages, there’s always something new to learn

mark's technic world 807

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

从Java到Groovy——Differences with Java

Groovy与Java的比较

xu_fu的专栏 978

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Groovy Differences with Java(Groovy不同于java的地方)

Groovy tries to be as natural as possible for Java developers. We’ve tried to follow the principle of least surprise when designing Groovy, particularly for developers learning Groovy who’ve come from

doubleping的专栏 641

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Groovy 语言本身具有简洁、灵活的特点,使得测试代码的编写更加高效

- **丰富的框架、库和工具**:Groovy 社区非常活跃,开发出了大量的框架、库和工具。这为开发者提供了丰富的选择,能够满足不同场景下的开发需求,从而提高开发效率。

[Blog][Domain] programb.blog.youkuaiyun.com 473

Torchvision 数据集 API 文档生成机制:深入解析 class_dataset.rst 的 Sphinx autodoc 模板

`docs/source/_templates/class_dataset.rst` 是 Torchvision 文档构建体系中负责自动生成**数据集(Dataset)类 API 参考页面**的 Sphinx 模板:每当 `docs/source/datasets.rst` 中通过 `autosummary` 罗列一个数据集类(如 `CIFAR10`、`INaturalist`、`KittiFlo

gitblog_00198的博客 352

终极WinMerge过滤器指南:告别冗余文件干扰的7个实用技巧

你是否曾在使用WinMerge进行文件夹比对时,被大量无关的日志文件、编译产物和缓存文件淹没,导致真正重要的差异被隐藏?作为Windows平台上最强大的开源差异比较工具,WinMerge的过滤器功能正是解决这一痛点的终极利器。本文将为你详细介绍如何利用WinMerge过滤器精准排除干扰文件,通过7个实用技巧让文件夹比对效率提升80%,专注于真正需要关注的差异。 ## 用户痛点分析:为什么你需要过

gitblog_00481的博客 296

JMeter集成Python操作DB2数据库:提升性能测试脚本灵活性与数据处理能力

在性能测试与接口自动化领域,数据库操作是核心环节。关系型数据库如DB2,其连接与操作通常依赖JDBC等标准接口,但面对复杂的数据生成、JSON/XML解析或特定SQL逻辑时,脚本的灵活性与可维护性面临挑战。此时,引入Python这一具备丰富生态的脚本语言,通过其pandas、sqlalchemy等库,可以高效处理数据构造与比对等复杂任务。其技术价值在于,将JMeter的负载模拟调度能力与Python强大的数据处理能力相结合,形成优势互补的工程实践方案。这一模式特别适用于需要在压测前后进行自动化数据准备、校验

weixin_33681778的博客 368

ioS开发--Warning警告处理

去除警告的方法: #pragma clang diagnostic push #pragma clang diagnostic ignored"-Wunused-function" local void free_linkedlist(ll) linkedlist_data* ll; { free_datablock(ll->first_block); ll->first_blo

zzzzzdddddxxxxx的专栏 1万+

Groovy Convert between string and date

Reference: http://java.dzone.com/articles/groovy-jdk-gdk-date-and http://www.javabeat.net/2008/09/sample-code-for-simpledateformat/ //String to Date import java.util.Date def newDate ='

markinlqx的专栏 3215

Groovy入门

groovy

建伟博客 1158
上一篇: 案例研究:利用Grails搭建Feedlr.com网站
下一篇: Groovy与Java的区别
hxpjava1
博客等级 码龄19年 1365粉丝 511原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值