6

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!

1
  • 2
    it's not clear what you ultimately want, but there is no equivalent to python's metaclasses in scala. If you want to get a class from a String, you should use Class.forName. Commented Apr 30, 2011 at 9:38

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Thanks - can you think of any other general way to get a a string representation from a class type and then be able to instantiate a new object of that class from that string?
@Heinrich See Randall's answer. Once you have a java.lang.Class, you can call newInstance on it. However, if you want to find all subclasses of a class, ask a Java question about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.