Hello, this is a common problem that I always have when I use different languages, for example in Smalltalk you can do something like:
aClass allSubclasses
What about other languages? Like Java? PHP? Python?
Please post snippets!
Hello, this is a common problem that I always have when I use different languages, for example in Smalltalk you can do something like:
aClass allSubclasses
What about other languages? Like Java? PHP? Python?
Please post snippets!
In PHP you can do this:
function getSubclasses($parentClassName)
{
$classes = array();
foreach (get_declared_classes() as $className)
{
if (is_subclass_of($className, $parentClassName))
$classes[] = $className;
}
return $classes;
}
var_dump(getSubClasses('myParentClass'));
Of course, you can dynamically load in classes, so this will only give you classes that happen to be loaded at the time you call the function.
Python. No.
You can, of course, implement this by creating a metaclass to save all the distinct classes that show up when __new__
is called.
I doubt it's more than two or three lines of code.
Sidebar
If this is a common problem you always have, perhaps you need a better IDE, or a better tool for generating API documentation from your code.
In C# you can use IsAssignableFrom: "Determines whether an instance of the current Type can be assigned from an instance of the specified Type" http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx
Ruby 1.9 with nifty chained iterators:
#!/usr/bin/env ruby1.9
class Class
def subclasses
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
end
Ruby pre-1.9:
#!/usr/bin/env ruby
class Class
def subclasses
result = []
ObjectSpace.each_object(Class) { |klass| result << klass if klass < self }
result
end
end
Use it like so:
#!/usr/bin/env ruby
p Numeric.subclasses
In Java, with eclipse you you right click and click open type hierarchy, which will show you all subclasses.
Python:
Use the special attribute __subclasses__
:
class A(object):
pass
class B(A):
pass
class C(A):
pass
A.__subclasses__()
result:
[<class '__main__.B'>, <class '__main__.C'>]
If you need sub-subclasses, code a recursive method