Java - Load a class outside of classpath. What are the options

不打扰是莪最后的温柔 提交于 2021-02-05 07:49:23

问题


I got a Java product which is used by many clients. The product gets added as a jar into the client's (say for example XYZ company who wants to use his product for their needs) code base and works independently. Its a stand alone product and all the client projects depends (maven dependency) on this one product (which again is a couple of java projects bundled as a jar rolled out with a license)

Now i am in a situation to make the engine use a class outside of it's class path. It's a client class and I don't want to move that class into the products code base and keep it outside but still want to use it.

Just to confirm I tested it and its saying that class not found as expected. One option i can think of is jar those specific classes and add it to my product's classpath

Is their any other better ideas?


回答1:


I think you have three options (EDIT -- more details):

  1. load a class from a File on the filesystem, using a URLClassLoader:

    see this answer;

  2. create the class using reflection:

    you still need the class to be in classpath, or you need to load it through filesystem (option 1), see this.

  3. middle way solution: you can add an interface to your standalone product, and then create your implementing class with reflection; I never did this in production, I just tested the code and it works: see this question



来源:https://stackoverflow.com/questions/24286379/java-load-a-class-outside-of-classpath-what-are-the-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!