Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get all the subclasses of a class? [duplicate]

Possible Duplicate:
How do you find all subclasses of a given class in Java?

Hi,

I would like to get a list of classes that implement an interface in Java at runtime so I can do a lookup service without having to hard code it. Is there a simple way of doing this? I fear not.

like image 348
Chris Wilson Avatar asked Jul 06 '09 14:07

Chris Wilson


People also ask

What do subclasses not inherit?

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods.

How do you find all the subclasses of a class given its name?

If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__ as above. However you find the class, cls. __subclasses__() would then return a list of its subclasses.

Can a class have multiple subclasses?

Keep in mind that you cannot choose multiple subclasses for the same class. You could, theoretically get 9 subclasses (assuming you meet the multiclassing requirements) with Cleric, Warlock, Sorcerer, Wizard, Druid, and any other 4.


1 Answers

The short answer is no.

The long answer is that subclasses can come into existence in many ways, which basically makes it impossible to categorically find them all.

You can't do it at runtime but you can't find classes until they're loaded and how do you know they're loaded? You could scan every JAR and class file but that's not definitive. Plus there are things like URL class loaders.

Inner classes (static and non-static) are another case to consider. Named inner classes are easier to find. Anonymous inner classes are potentially much more difficult to find.

You also have to consider that if a class has subclasses then new subclasses can be created at a later point.

like image 120
cletus Avatar answered Sep 17 '22 15:09

cletus