-1

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.

1
  • You're probably looking for the reflection mechanism in Java. Commented Jan 17, 2015 at 23:29

2 Answers 2

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. :)

Sign up to request clarification or add additional context in comments.

4 Comments

Technically speaking you're not creating classes.
@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.
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.
Thank you for the answer Todd. It looks exactly like what I need.
0

you could generate a random number from 1 - 9 and use a switch statement where each case calls a different class

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.