Skip to main content
gamedev.net
🔒 Locked

[java] java reflection + dynamic cast

Started by Kaze 6 replies 4.6k views
Original Post
Kaze
Kaze
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
ToohrVyk
ToohrVyk
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).
Kaze
Kaze
thanks anyway, i was hopping there was a better solution but it shouldn't be too hard either way
Son of Cain
Son of Cain
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
Kaze
Kaze
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.
Son of Cain
Son of Cain
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
Sneftel
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.)
nmi
nmi
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).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.