2011-05-11 29 views
2

我來自Java,想知道是否可以使用自省爲對象設置實例變量。如何通過自檢來判斷某個方法是讀寫,只讀還是隻寫?

舉例來說,如果我有下面的類聲明,與兩個實例變量,first_attributesecond_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中做到這一點?

+0

好消息:在attr_accessor或attr_reader之後不需要分號。 – 2011-05-11 23:25:01

+0

非常類似的問題: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

回答

4

有沒有真正的內置像Java屬性的東西什麼,但你可以做到這一點很容易地像這樣:

self.class.instance_methods.grep(/\w=$/) 

將返回的類上的所有setter方法的名稱。

+1

'attr_reader:x'增加'x'方法,這是一個getter。 'attr_writer:x'增加'x ='方法,這是setter。 'attr_accessor:x'都可以。總之,通過使用這些「宏」,您可以將方法添加到您操作字段的類中。所以奧斯汀泰勒是正確的;僅將實例方法過濾到以單個「=」結尾的用戶,並獲得setter方法。如果你有5個額外的分鐘,請看這篇簡短的文章:http://www.rubyist.net/~slagell/ruby/accessors.html – dimitarvp 2011-05-11 15:45:04

+0

請注意,在Ruby中,當定義新類時,實際上會在'Class 'context,所以'self.class.instance_methods'和'self.instance_methods'的使用取決於寫入的上下文。當前者**內**方法定義和後**外**方法定義時,它們產生相同的結果。 – Laas 2011-05-11 18:45:59

相關問題