寻找一种方法来保存对 class 的引用,以便我以后可以动态实例化它

Looking for a way to hold a reference to a class so that I can dynamically instantiate it later

我创建了 this playground 这应该可以使我的问题更清楚,但简而言之,我正在寻找一种方法将对 class 名称的引用传递给另一个 class 的初始化程序,以便在编译过程的后期我可以实例化 class 并用它做一些事情。

class Route
  property action : Class

  def initialize(@action)
  end

  def do_something
    @action.new.call
  end
end

class Action
  def call
    puts "called"
  end
end

route = Route.new(Action)

然而,以上给了我 can't use Object as the type of an instance variable yet, use a more specific type

我知道这可能还没有用语言实现,但我想知道是否有另一种方法可以实现这一点,因为我不能真正按照错误建议的那样做,并且更具体,因为我需要接受任何 class.

希望有人能给我指出正确的方向...

提前致谢!

尝试泛型:

Crystal, 233 字节

class Route(T)
  property action : T

  def initialize(@action)
  end

  def do_something
    @action.new.call
  end
end

class Action
  def call
    puts "called"
  end
end

route = Route(Action.class).new(Action)
route.do_something

Try it online!