Skip to content

Commit 28cc4b3

Browse files
authored
Merge pull request eugenp#8464 from kwoyke/BAEL-3734
BAEL-3734: Fix Groovy Metaprogramming examples
2 parents 07e030e + f00c6d6 commit 28cc4b3

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@ package com.baeldung.metaprogramming.extension
22

33
import com.baeldung.metaprogramming.Employee
44

5+
import java.time.LocalDate
6+
import java.time.Year
7+
58
class BasicExtensions {
69

710
static int getYearOfBirth(Employee self) {
8-
return (new Date().getYear() + 1900) - self.age;
11+
return Year.now().value - self.age
912
}
1013

1114
static String capitalize(String self) {

core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package com.baeldung.metaprogramming
22

3-
import groovy.time.TimeCategory
3+
4+
import java.time.LocalDate
5+
import java.time.Period
6+
import java.time.Year
47

58
class MetaprogrammingUnitTest extends GroovyTestCase {
69

@@ -51,14 +54,16 @@ class MetaprogrammingUnitTest extends GroovyTestCase {
5154

5255
void testJavaMetaClass() {
5356
String.metaClass.capitalize = { String str ->
54-
str.substring(0, 1).toUpperCase() + str.substring(1);
57+
str.substring(0, 1).toUpperCase() + str.substring(1)
5558
}
5659
assert "norman".capitalize() == "Norman"
5760
}
5861

5962
void testEmployeeExtension() {
60-
Employee emp = new Employee(age: 28)
61-
assert emp.getYearOfBirth() == 1992
63+
def age = 28
64+
def expectedYearOfBirth = Year.now() - age
65+
Employee emp = new Employee(age: age)
66+
assert emp.getYearOfBirth() == expectedYearOfBirth.value
6267
}
6368

6469
void testJavaClassesExtensions() {

0 commit comments

Comments
 (0)