0

I'm making a small (for fun) game where virtual robots fight each other. I have an array of names of the classes of these robots, but I don't know how to load them. It's probably clearer in codes:

String[] classes={"Bot1","Bot2","Bot123"};
Object[] bots=new Object[classes.length];

for(int i=0;i<classes.length;i++){
  bots[i]=UnknownFunction(classes[i]);
}

Additional details:

package Arena;

public class Bot {
    public void main(String args[]){

    }

    public void init(){
        System.out.print("Loaded");
    }
}

In the main file:

bot=Class.forName("Arena.Bot").newInstance();
bot.init();
1
  • Do you want to get to a Class object like the one you get from String.class or do you want an instance of that class like in new String()? Commented Nov 22, 2012 at 21:21

2 Answers 2

1

You need Class.forName() method to load your class, and then newInstance() method to instantiate them. Assuming that you have a 0-arg constructor in them: -

bots[i] = Class.forName(classes[i]).newInstance();

Also note that, those class names has to be fully qualified names.

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

9 Comments

Thanks for your response. How would I get the fully qualified names?
@Linksku.. That you would have to give. Fully qualified class names means package.subpackage.classname. For e.g: - pkg1.YourClass.
I think I've managed to load the classes (try/catch does not return any errors), but I'm unable to run any methods in the classes. I always get "The method init() is undefined for the type Object".
@Linksku.. What method are you invoking? Can you post the code? Edit your question to add it.
I edited the question. I'm trying to run init(), but it always returns an error.
|
0
String[] classes = {"Bot1", "Bot2", "Bot123"};
Object[] bots = new Object[classes.length];

for(int i = 0; i < classes.length; i++)
{
    bots[i] = Class.forName(classes[i]).newInstance();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.