如何重写扩展Java类的Ruby类的构造函数



具有

class Object
  alias :old_initialize :initialize
  pause_warnings
  def initialize
    old_initialize
    print "BOOM"
  end
  resume_warnings
end

然后

class Foo < SomeJavaClass
  def initialize
    super()
  end
end

为什么当我创建Foo对象时,它没有打印?

pause_warningsresume_warnings简单地修改$VERBOSE

您对使用模块有何看法?

module MyModule
  def self.included base
    class << base
      alias_method :old_new, :new
      define_method :new do |*args| # You can also use `def new(*args)` if you don't mind the scope gate
        pause_warnings
        old_new(*args).tap do |instance|
          print "BOOM"
          resume_warnings
        end
      end
    end
  end
end

用法如下:

class Foo < SomeJavaClass
  include MyModule
end

几个小提示:

1( 由于我使用了Rubinius,所以无法在JRuby上对此进行测试。

2( 行为略有不同。在代码中,您可以暂停警告,定义initialize方法,然后继续警告。在我的代码中,我暂停警告,创建对象,然后继续警告。这意味着警告将在代码中暂停/恢复一次(在类定义中(,而在我的代码中警告将暂停/恢复多次(在对象创建中(。我不确定这里的正确行为是什么。如果您想要相同的行为,只需将暂停/恢复警告移动到define_method块的上方/下方(而不是内部(。

3( 您的代码为对象分配内存,然后调用您的initialize方法。我的代码在为新对象分配内存之前执行代码。

我认为你应该试试这个,

根据你的问题,你想覆盖对象类构造函数,就像这个一样

class Object
  def initialize
    super() # This will call old initialize method.
    print "BOOM"
  end
end
class Foo
  def initialize
    super()
  end
end
Foo.new()
#BOOM => #<Foo:0x9e66500>

最新更新