[java] java reflection + dynamic cast

Started by
6 comments, last by nmi 17 years, 1 month ago
so basically for a project im working on im trying to create a plugin system, to do this im loading the class as a class object from a class file, then using the java reflection api to see what methods it has and call them. My question, is there any way i can cast a object as a interface that it dosen't implement but i have confirmed it has all the required methods EDIT: I could create a dummy class that implement the interface and invokes the appropriate method object but this is a rather messy solution
Advertisement
Probably not. You can, however, create a wrapper which implements the interface and forwards calls through reflection (if you have control over what the interface is).
thanks anyway, i was hopping there was a better solution but it shouldn't be too hard either way
No, it is not possible. But why would you want that? Clarify your reasons, and we might be able to suggest something for you [grin]
a.k.a javabeats at yahoo.ca
The project is for a encryption application
basically the project already has a working release and can use different algorithms stored in there own class that implement a interface, I want to add the ability to dynamically load new algorithms from external classes at runtime, i need it to be in the form of a object cast a the interface to avoid major re-coding. A class that stores methods and implements the interface isn't too bad of a solution, i was just curious if there was a better way.
I know what you mean, but unfortunately, all the possible workarounds for that that I can think of are not worth the trouble if compared to the classic solution. =[
a.k.a javabeats at yahoo.ca
Make an adapter class which implements the required interface and calls the preexisting module's functions. (Requires a new adapter class per real class, but if you're dealing with a preexisting body of code that's a finite number.)
Quote:Original post by Sneftel
Make an adapter class which implements the required interface and calls the preexisting module's functions. (Requires a new adapter class per real class, but if you're dealing with a preexisting body of code that's a finite number.)

Or generate one using a bytecode assembler (like BCEL).
Or write a custom classloader that transforms thoses classes by adding the interface to that class (since it alrady implements it with its functions).

This topic is closed to new replies.

Advertisement