Ruby中的反射(Reflection)应用实例

在Java语言中,提供了发射机制,通过发射机制可以通过字符串构造出这个对象,可以获取对象的所有方法(包括私有方法),可以调用私有方法,可以更改成员变量的值(包括私有的成员变量)。
Ruby也是面向对象的高级语言,当然也提供了反射机制,今天我们讨论通过类名称构造类对象的功能。

一、通过类名称构造类对象

我们先看普通的构造:

module ModuleA

    #the class name, later we will use it to create the corresponding object

    CLASS_NAME_OF_WOOD = "ModuleA::Wood"

    CLASS_NAME_OF_WOODDESK = "ModuleA::WoodDesk"

    CLASS_NAME_OF_WOODCHAIR = "ModuleA::WoodChair"

    class Wood

        def initialize

            @desc = "I am a primal wood"

        end

        def say

            puts @desc

        end

    end

    class WoodDesk < Wood

        def initialize

            @desc = "I am a desk made of wood"

        end

        def say_private

            puts "actually, i have some bug but no public"

        end

        public :say

        private :say_private

    end

    class WoodChair < Wood

        def initialize

            @desc = "I am a chair made of wood"

        end

        def say_private

            puts "I Want get married with a WoodDesk..."

        end

        def smile

            puts "ha hah hah haha ...."

        end

        public :say

        private :say_private, :smile

    end

end

以上是 Ruby中的反射(Reflection)应用实例 的全部内容, 来源链接: utcz.com/z/326148.html

回到顶部