Java-在类路径之外加载一个类.有什么选择 [英] Java - Load a class outside of classpath. What are the options
问题描述
我得到了许多客户都在使用的Java产品.该产品以罐子形式添加到客户的代码库中(例如,要使用其产品以满足其需求的XYZ公司),并且可以独立工作.它是一个独立的产品,所有客户项目都依赖于(maven依赖)该产品(这又是将两个Java项目捆绑成一个带有许可证的jar捆绑在一起的Java项目)
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?
推荐答案
我认为您有三个选择(编辑-更多详细信息):
I think you have three options (EDIT -- more details):
-
使用
URLClassLoader
从文件系统上的文件加载类:
load a class from a File on the filesystem, using a
URLClassLoader
:
使用反射创建类:
您仍然需要将类放在类路径中,或者需要通过文件系统(选项1)加载它,请参阅.
you still need the class to be in classpath, or you need to load it through filesystem (option 1), see this.
中间方法:您可以向独立产品添加接口,然后使用反射创建实现类;我从未在生产中这样做过,我只是测试了代码,它的工作原理是:看到此问题
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
这篇关于Java-在类路径之外加载一个类.有什么选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!