Heinrich Schmetterling
Heinrich Schmetterling

Reputation: 6894

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!

Upvotes: 6

Views: 946

Answers (2)

Randall Schulz
Randall Schulz

Reputation: 26486

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.

Upvotes: 4

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297275

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

Upvotes: 2

Related Questions