Over a million developers have joined DZone.

Groovy Goodness: Using Project Coin Features Also With Older Java Versions

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Since Groovy 2 we can use a subset of the Project Coin features from Java 7. But we don't have to run Java 7 to use them in Groovy code. We can use the new features even if we run our Groovy code on older Java versions.

Groovy didn't have to add all Project Coin features, because some are already supported in Groovy, like the switch statement on String objects or diamond operator. A feature that is added is a syntax enhancement to define binary literals. We can now use binary integral literals by prefixing the value with 0b:

// Binary notation.
int x = 0b101
assert x == 5

The underscore in number literals is now supported in Groovy. We can define numbers and use an underscore to make them more readable. The value is not changed:

import static java.text.NumberFormat.getInstance as formatter
import static java.util.Locale.US

// Use underscore for number literals.
double d = 89_192.29
assert formatter(US).format(d) == '89,192.29'

long longNumber = 1230_3910_1929_182931
assert longNumber == 123039101929182931

int length = 5_10
assert length == 510

long hex = 0x00_ff
assert hex == 255

We can define a multi-catch exception in Groovy 2. We specify more than exception in the catch clause separated by a pipe (|) symbol:

import java.lang.reflect.*

// Multicatch.
class Person {
    String name

try {
    final Person p = new Person(name: 'mrhaki')
    final Method toString = p.class.getMethod("toString1", null)
    final Object result = toString.invoke(p, null)
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    assert e

(Code written with Groovy 2.0.4)




Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}