I am trying to figure out an effective way of getting a random class from my project. There are nine different classes(ten including the startup), each one with a different behavior(which extend a declaratoid class that is used in the main function). I need to be able to have the function to run differently on each startup. What do I need to do? Edit:Thanks for the answer, but I am now running into another problem. I have to pass the result as the first parameter in another the function now.
Asked
Active
Viewed 78 times
0
-
You're probably looking for the reflection mechanism in Java. – Michał Szydłowski Jan 17 '15 at 23:29
2 Answers
3
Create a factory method that gets a random number and creates an object based on that, in a switch:
public static YourInterfaceType createRandom() {
Random r = new Random();
switch(r.nextInt(10)) {
case 1: return new FirstType();
case 2: return new SecondType();
// etc
default: return new LastType();
}
}
Edit More exact definition of words. :)

Todd
- 30,472
- 11
- 81
- 89
-
-
@aioobe I took the intent to mean instances of already defined classes. If OP provides more detail and this is off the mark, I'm happy to remove it. – Todd Jan 17 '15 at 23:34
-
He was referring to your statement `and creates a class based on that` - not true. It's creating an instance of an existing class, not creating a class. – gknicker Jan 17 '15 at 23:36
-
Thank you for the answer Todd. It looks exactly like what I need. – Aaron Cottrill Jan 18 '15 at 16:32
0
you could generate a random number from 1 - 9 and use a switch statement where each case calls a different class

Lance
- 19
- 5