Search code examples
jruby

JRuby anonymous classes


How to access the parent class variables from an anonymous class in JRuby?
(without using static variables)

class MyJRubyClass  
    def initialize  
        @var1 = 1  
        @var2 = Class.new{  
            def Method1  
                @var1 = @var1 + 1  
                print @var1  
            end  
            }.new  
        @var2.Method1()  
    end  
end  

Thank you.


Solution

  • it always needs a bit of time (and practice) to get used to a new language. the concept of Java's inner classes having 'exclusive' parent class access has no adequate in Ruby.

    while its useful for related classes to co-operate on the internals, from an OOP stand-point it's not blessed as objects should be "black-boxes" cooperating using messages. this is somehow Ruby's approach.

    on the other hand Ruby does not hide anything as it has reflection APIs to e.g. retrieve instance variables (the example prefers exposing an attribute reader/writer) :

    class MyJRubyClass
      attr_accessor :var1
      def initialize  
        @var1 = 1  
        klass2 = Class.new do
          def initialize(parent); @parent = parent end
          def Method1
            print @parent.var1 = @parent.var1 + 1
            # without attr accessor : 
            #var1 = @parent.instance_variable_get(:@var1)
            #@parent.instance_varialbe_set(:@var1, var1 + 1)
          end  
        end  
        @var2 = klass2.new(self)
        @var2.Method1()
      end  
    end