Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Dynamically Load Multiple Versions of Same Class

What I'd like to be able to do is to load set of classes, probably all in the same folder. All of which implement the same interface and are the same class, then in my code I'd like to be able to call functions on those classes.

like image 318
JonLeah Avatar asked Nov 10 '09 05:11

JonLeah


4 Answers

Based on your answer to my question, it seems you want to define a game interface and then plug in any number of AI implementations, probably configured from a .properties file. This is fairly standard use of an API interface.

You define an EngineInterface providing a method that accepts game state and returns the move. Then you define multiple classes that all implement EngineInterface. Your driver reads a property file to get the names of the implementation classes, instantiates them with Class.forName() and stores them in a list and/or map. Then when the driver gets requests it invokes each implementation in turn and keeps track of the results.

like image 176
Jim Garrison Avatar answered Sep 28 '22 10:09

Jim Garrison


Have you tried something like:

class Move;   // some data type that is able to represent the AI's move.

interface AI {

    Move getMove( GameState state);
};

AIOne implements AI;
AITwo implements AI;

Each class would implement its own algorithm for generating a move, but would be called but called by common method

like image 45
Dave L Delaney Avatar answered Sep 28 '22 09:09

Dave L Delaney


It is possible to do what you want with OSGI but you could as well use a custom classloader. The idea is that you have to instanciate a classloader for every version of the class you want to load. Here you can find a good explanation.

But I think what you really need to solve your problem is something based on interfaces like described by Jim Garrison or Dave L Delaney...

like image 31
pgras Avatar answered Sep 28 '22 08:09

pgras


  1. If you can use OSGI, its as simple as snapping a finger! In oSGI you can have multiple verssions of the same class. All you do is have same bundles with different versions.

  2. Otherwise you can still write your custom class loader that reads both the classes. One way of doing it would be like this. You write two ClassLoaders, one of them loads one version of the class and the other loads the other version of the class. Now based on the need you choose the classloader1 or classloader2 to load the class. So now you can also have multiple versions of the same class loaded simultaneously in the memory.

Note: Make sure this is actually you want to do, there may be other ways of coming around your problem.

like image 34
Suraj Chandran Avatar answered Sep 28 '22 09:09

Suraj Chandran