When Ruby Does Java Privacy17 Nov 2015
Ruby has little respect for privacy or private state. There sure is “sugar” such as
private_constant but none of these really hide anything away much,
it’s a very flexible language after all.
Java on the other hand gets a bit restrictive, with respect for
enforced by the compiler.
Let’s see how JRuby fits the two together in the context of retrieving classes.
Obviously, public Java classes simply work as if it they were from Ruby-land :
Contrary, private or package-only Java classes are hidden as if they did not exist.
private_constant to make sure constants are only visible in the declared
(module) context but nowhere else.
Turns out this fits non-public Java classes nicely. Let’s showcase an example.
Suppose we’d like to be able to detect whether a
java.util.List instance is synchronized
(naively assuming list types are only those available with the standard collections framework) :
As expected the non-public inner
SynchronizedList in Ruby scripts behaves
similarly to how it does in raw Java - only accessible in the enclosing class and not being
part of the exported API.