如何覆盖扩展Java类的Ruby类的构造函数?

时间:2014-06-04 00:47:32

标签: java ruby jruby

有无

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

2 个答案:

答案 0 :(得分:2)

您对使用模块有何看法?

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)行为略有不同。在代码中,您暂停警告,定义初始化方法,然后恢复警告。在我的代码中,我暂停警告,创建对象,并恢复警告。这意味着警告将在您的代码中暂停/恢复一次(在类定义上),并且警告将在我的代码中暂停/恢复多次(在对象创建时)。我不确定这里的正确行为是什么。如果你想要相同的行为,只需在define_method块上方/下方移动暂停/恢复警告(而不是在其中)。

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

答案 1 :(得分:0)

我认为你应该试试这个,

根据您的问题,您想要覆盖对象类构造函数,请执行此操作

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>