Search code examples
javarubynested-classrjb

How to access nested static classes using Rjb?


Lets say a Java program defines the class A, which has a nested static class 'B'.

How is it possible to access class B using the Ruby-Java Bridge?

For example, these attempts do not work:

A = Rjb::import('package.A')
A.B 
A::B

Is there a way to accomplish this?


Solution

  • Google cached this result from 2006. Sounds reasonable though, so take it and experiment!

    (PS: I'm a java + ruby user, but never used Rjb, so just passing along the info...)

    http://webcache.googleusercontent.com/search?q=cache:1p7OdptgsYUJ:blog.voneicken.com/2006/12/3/accessing-inner-java-classes-via-rjb+inner+class+rjb+ruby+java&cd=10&hl=en&ct=clnk&gl=au

    I couldn’t resist investigating the issue Les had with accessing static inners and I think I found the syntax. Accessing inner classes (static or not) can look a little wonky but it is doable. Statics are loaded like any other class, but their pathname is ‘OuterClass$StaticInnerClass’. The nonstatic inner classes are a tiny bit trickier. Import like the static, with ‘OuterClass$Inner’; now you have the inner class, but the trick is in instantiating an instance: you must provide an OuterClass instance as the first argument to the constructor (thus revealing a little behind the curtain of java the implicit access an inner has to its outer’s methods and data):

    Outer = Rjb::import(‘Outer’)
    Inner = Rjb::import(‘Outer$Inner’)
    StaticInner = Rjb::import(‘Outer$StaticInner’)
    
    outer = Outer.new
    inner = Inner.new(outer)
    staticInner = StaticInner.new