scala:类似于 python 中的元类?
在 scala 中,我需要实现类似于 python 元类的东西。就我而言,使用元类的目标通常是创建特定基类的所有子类的注册表 - 即从类的字符串表示形式到对该类的引用的映射。在Python中,将元类放在基类上非常方便,这样就不需要对每个子类执行任何特殊操作。我希望在 scala 中做类似的事情。有什么方法可以模拟元类,或者以不同的方式做到这一点?谢谢!
in scala i need to implement something similar to python metaclasses. in my case the goal of using the metaclasses is usually to create a registry of all the subclasses of a particular base class - that is, a mapping from say a string representation of the class to a reference to the class. in python it's very convenient to put a metaclass on the base class so that nothing special needs to be done on every subclass. i'm looking to do something similar in scala. is there any way to emulate metaclasses, or otherwise do this a different way? thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您知道类的完全限定名称,则可以使用
java.lang.Class
中常用的 Java 反射方法加载它,即Class.forName(String fqClassName)
。给定Class
的结果实例,只有存在零参数构造函数,实例化才容易,否则您会陷入所有 Java 反射类型的混乱世界。如果您想要一种“发现”,其中类在编译时未知并且其名称未以某种方式作为程序的输入或参数提供,那么类加载器方法可能是唯一的答案。
If you know the fully qualified name of the class, you can load it using the usual Java reflection methods in
java.lang.Class
, namelyClass.forName(String fqClassName)
. Given the resulting instance ofClass
, instantiation is easy only if there's a zero-argument constructor, otherwise you get entangled in the messy world of all the Java reflection types.If you want a kind of "discovery" where classes unknown at compile time and whose names are not supplied as an input or parameter of the program in some way, then the classloader approach is probably the only answer.
没有什么类似于 python 的元类。您所说的注册表可能可以使用自定义类加载器或反射。
There's nothing similar to python's metaclasses. The registry you speak of might be possible using custom class loaders or reflection.