tags:

views:

132

answers:

2

So question 194698 shows how to load a jar file at runtime and you can load individual named classes and get a Class object. Now my problem is I want to be able to cast those Classes to the types they really are, but I can't because I can't use an import since the whole point is to load it at runtime rather than compile time.

It seems like the way to go is to use reflection to discover the functions and field names, but that seems brittle since the API in the jar files could change and the code won't break until it is run.

Is there a better way?

+3  A: 

The usual way is to use the dynamically loaded classes via a well-defined interface (as is shown in the accepted answer of the question you linked, with Runnable). That way their implementation details can change freely, as long as they implement the interface. So you cast the instance of the loaded class to that interface inside a try block, catch and handle the ClassCastException in case the class does not implement the interface (this is not shown in the answer referred above but is trivial to add), or else use it happily ever after.

Péter Török
Yeah that makes sense.
justinhj
+1  A: 

If you don't know what classes are available nor what the interface they have is, there is no or very little possibilities for you to use them ( people struggle knowing the interface already )

Generally this "extension" modules are coded to an specific interface, so the new loaded classes will always have certain methods ( ie, a JDBC driver always expect to find a PreparedStatement implementation, a ResultSet etc. etc even when it doesn't know what else is underneath )

In your case and if you want to load and use arbitrarily classes, the only remaining resource I see, is to provide some mechanism to add an scripting language ( such as Groovy, Jython or JRuby ) and code to the discovered interface.

OscarRyz