Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random selection from a heap of classes in Java

I have a best technique issue in Java. I have a base class implementing some genral methods. An a heap of inherited classes. Now I have to randomly select one of the inherited classes. My approach is the following:

  1. Having a array of the Class object for each inherited class
  2. Randomly generate an index for the array
  3. Create an instance of the class object at the random index from 2. with newInstance()

Code exmaple for step 1:

Class[] possibleClasses = {Class1.class, Class2.class}

Is this a sufficient approach? For example the Eclipse Indigo syntax correction says for the code example above "Class is a raw type. References to generic type Class should be parameterized". So the definition without generic type may has side effects or so?

Stefan

like image 451
Stefan Avatar asked Jun 29 '26 12:06

Stefan


1 Answers

Your approach is fine - indeed it's probably the simplest and most effective approach.

If you want to avoid the compiler warning you can add a generic type argument as follows:

Class<?>[] possibleClasses = new Class[]{Class1.class, Class2.class}

However this just gives you a different warning (unchecked conversion) so you might as well just suppress the original warning directly.

A slightly more complex alternative approach would be to use reflection to walk the class hierarchy and automatically add all subclasses of your base class to an ArrayList of classes. The advantage is that you wouldn't need to explicitly list out all the subclasses individually and it would automatically pick up any new subclasses added.

like image 165
mikera Avatar answered Jul 01 '26 01:07

mikera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!