简体   繁体   中英

Java override native classes after loading

So my problem is very simple, I got a plugin management program that allows plugins to be loaded and run AFTER the initial program got launched. All that works fine, I can load and unload the classes as I wish but the problem I encountered now is the following:

I am now trying to write a plugin to that plugin management system which is going to take care of all networking to prevent every plugin to host its own connection. The problem is that I can't use bootstrap classes as the plugins are loaded dynamically on runtime (I don't even know if it's there till I look for it and load it) yet I do still want to override the normal socket class to filter what's going on. Same goes for other classes that I want to override using plugins so that other plugins trying to use those classes and their functions will no longer be able to access the native implementation but instead will have to go through my implementation of it. Don't ask, I have reasons :P

So all just put together shortly: I need a way to dynamically on runtime override native classes with my own implementations of them so that everything else I load will use my implementation instead of the native one. Any ideas?

Depending on how the dynamic class loading works, this is probably not possible (you need to provide more details to be sure, but if it's using a new ClassLoader per plugin, you can't override system classes from it)

But for your specific problem, namely to provide your own implementation of network sockets, there is a much better solution.

You need to implement java.net.SocketImplFactory and call Socket.setSocketImplFactory , as well as ServerSocket.setSocketFactory with an instance of your factory. (Don't ask me why these two methods are not named the same)

Your factory should then create your subclass of SocketImpl that can do all networking in its own way.

You should not override Socket . Just use Socket.setSocketFactory to provide your own implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM