views:

1418

answers:

6

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!

+2  A: 

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.

Greg
A: 

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.

S.Lott
A: 

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

jcollum
Does that get you all subclasses? Or do you have to make that test for each class currently defined?
S.Lott
+2  A: 

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
Jörg W Mittag
i <3 ruby - so clean.
Jarrod Dixon
A: 

In Java, with eclipse you you right click and click open type hierarchy, which will show you all subclasses.

shsteimer
+1  A: 

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

Alexandre
Wow, really nice, didn't know this :) thanks!
ClaudioA