Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: analogy to metaclasses in python?

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!

like image 763
Heinrich Schmetterling Avatar asked Apr 30 '11 08:04

Heinrich Schmetterling


2 Answers

If you know the fully qualified name of the class, you can load it using the usual Java reflection methods in java.lang.Class, namely Class.forName(String fqClassName). Given the resulting instance of Class, 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.

like image 174
Randall Schulz Avatar answered Oct 10 '22 23:10

Randall Schulz


There's nothing similar to python's metaclasses. The registry you speak of might be possible using custom class loaders or reflection.

like image 33
Daniel C. Sobral Avatar answered Oct 10 '22 22:10

Daniel C. Sobral