我來自Java,想知道是否可以使用自省爲對象設置實例變量。如何通過自檢來判斷某個方法是讀寫,只讀還是隻寫?
舉例來說,如果我有下面的類聲明,與兩個實例變量,first_attribute
和second_attribute
:
class SomeClass
attr_accessor :first_attribute
attr_reader :second_attribute
def initialize()
# ...
end
end
我希望能夠得到實例的方法,大概是通過調用SomeClass.instance_methods
,知道哪些這些實例方法是讀/寫而不是隻讀。
在Java中我可以這樣做:
PropertyDescriptor[] properties = PropertyUtils.GetPropertyDescriptors(SomeClass);
for (prop : properties) {
if (prop.getWriteMethod() != null) {
// I can set this one!
}
}
如何在Ruby中做到這一點?
好消息:在attr_accessor或attr_reader之後不需要分號。 – 2011-05-11 23:25:01
非常類似的問題:http://stackoverflow.com/questions/4466541/is-there-a-better-way-to-get-the-public-properties-of-a-ruby-object – 2011-05-11 23:29:36