dynamically loading AI classes

how would i dynamically load a Java class from an inputstream? i intend to create a class for the AI for each type of character, then the game dynamically loads them. this should make the game easier to mod.
any suggestions?

:)thanks :slight_smile:

Check out reflection. It’s pretty slow though - you might be better off using scripting.

Recommending the use of scripting over reflection, because of performance considerations, is a bit questionable (at least ;))

What you want is an URLClassloader and loadClass()

Maybe this is just reflection again, bit couldn’t he export every AI script as a separate class file, and then execute it as part of the program? That has worked for me in the past.

Yeah scripting is the better way to go. Otherwise think “ClassLoader”.

If the intent is to allow others to create MODs, a scripting language would be easier for non-programmers to work with. Another alternative is to use a type of Plug-in system.

I made an RPG where you could have a special script for each level, basically I made a simple scripting language then got translated into Java so would be loaded by the ClassLoader.

Cool.
Where can I see the RPG?

You can look at its page here.

http://www.otcsw.com/bge2.php

I basically ended up making all the code except the combat engine and then lost interest. The level editor was pretty complex, though.

i had experimented a bit with loading classes using forname, and here’s something along the lines of what i’m using.

  public abstract class behavior {
public character avatar;

public behavior(Character c)
{
avatar=c;

}

public abstract void loop();
}

pseudocode for the character class because i'm too lazy to find it:

Class c = Class.forname(classname);

constructor con = g.getconstructor( Class{Character.Class});

instance = (behavior) con.newinstance(new Object{this});

instance.loop();


i believe this way, reflection is only used to load the class and create an instance. the rest should be able to take place at normal java speed.

It looks like your psuedo code, you have casting the loaded class to an interface. If you have an interface api setup, you have the code check a given directory for new classes and load them.
You could even do this during the run time of the game. But you will need to insure that the class is an instance of the interface to avoid errors.

so i would call getgenericinterfaces() on the class i loaded and check that it implements my interface?

If you have a Java Object already, all you need to do is

if (obj instanceof MyInterface) 

Then cast it to the interface and start using it. Otherwise, yes. You can use getGenericInterfaces() or getInterfaces(), which will give you the Class objects.

::)derp! why did i not remember that?