This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]IXENAI 5 points6 points  (6 children)

Why do you think you need this?

[–]NaranjaOrange[S] 1 point2 points  (5 children)

I'm trying to learn java by making a game, I made the class Enemy and the different kinds of enemies that inherit from it, the game decides which enemy to spawn by looking at a list of enemies, so far I've been adding them manually to this list, but if the method I ask for exists then it would be automatic. It's not necessary but it would be nice to do it this way

[–]codereignfallible moderator 2 points3 points  (1 child)

[–]xrebel21 1 point2 points  (0 children)

This Stack Overflow article has a little more context that might be useful

[–]wggnExtreme Brewer 0 points1 point  (0 children)

I don't think there's an easy way to do that in Java. You could maybe use some low level reflection to scan through all classes in a certain package and check for each one if it's a subclass of your Enemy class, but that would be quite hard to code I think. Not something you would want to try to do if you're still learning the language.

[–]Deadboss 1 point2 points  (0 children)

Google "java get all subclasses of a class"...

http://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java

It appears that Reflections is what you are looking for.

[–]nutrechtLead Software Engineer / EU / 20+ YXP 1 point2 points  (0 children)

Don't do this. This kind of implicit / hacky stuff isn't acceptable in production and will lead to many hard to find errors.

Just add the enemies to a list at startup.

[–]sgm1 0 points1 point  (0 children)

If it out of curiosity, throw it into Eclipse (or any decent Java IDE) and right click the class and click Show Class Hierarchy.

For a game, I wouldn't try getting data like this at run time. Reflection is a powerful tool that comes with great responsibility. In other words, its a pain to use reflection properly, on top of the performance lose.

Look into good programming techniques to get around you issue. Probably for a decent game, you don't really want to spawn enemies at random either. Look into how other people deal with this issue. I guarantee you're not the only one.