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?
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 theClassCastExceptionin 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.