Kirill
Kirill

Reputation: 8088

How to access public class member called 'properties'?

Suppose I have the following Java-class from 3rd party library:

public class Itm {
    public final Map<String, String> properties = ['foo': 'bar']
}

With the following code println new Itm().properties I expect to get a Map: [[foo:bar]]

But the result is:

[class:class Itm]

I realized that if I create the same class in Groovy, but declare properties field without public modifier, I get an expected result. But the class I work with has public access modifier. So in this case how can I access public field called properties, not default Groovy's getProperties(Object self)?

Upvotes: 2

Views: 771

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42262

You can use Groovy's direct field access operator obj.@field. This operator omits using the getter method and accesses the object field directly. Let's say we have the following Java class:

Itm.java

import java.util.HashMap;
import java.util.Map;

public class Itm {
    public final Map<String, String> properties = new HashMap<String,String>() {{
        put("foo", "bar");
    }};


}

And the following Groovy script that uses it:

println new Itm().@properties

The output is:

[foo:bar]

Upvotes: 2

Related Questions