gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:10 25 4
gpt4 key购买 nike

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

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

关于java - 如何覆盖扩展 Java 类的 Ruby 类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24027272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com