Load classes from a jar file from a url to memory and then run the main class out of all the classes

為{幸葍}努か 提交于 2019-12-11 01:57:13

问题


I'm trying to load classes from a jar file from a URL into memory then run one of the classes loaded. I don't want the class files or the jar to ever be accessible by the user. I've seen a couple similar questions, but they have gone unanswered.

I know it will probably use URLClassLoader and ByteArrayInputStream/ByteArrayOutputStream.

Thanks in advance for any help.

Similar unanswered questions:

How to load a jar from an URL without downloading it?

Load jar from URL


回答1:


You are on the right track (I think). The steps would be:

  1. Use URLConnection to open a stream to the JAR file.
  2. Read the stream and write it to ByteArrayOutputStream, and extract the byte array.
  3. Open a ByteArrayInputStream on the byte array, then wrap that in a JarInputStream.
  4. Iterate through the members of the entries of the JAR file, saving the entry information and buffering the entry file content in memory.
  5. Write a custom class loader that uses the in-memory cache of the JAR file entries and content.

I can't point you at example code because I couldn't find any.

(You pretty much have to cache stuff in memory since the JarFile API requires a RandomAccessFile and that implies that the data is in the file-system. On some systems you could create a temporary file, open a RAF on it, unlink it, and then fetch and write the URL into the RAF. But that isn't portable ...)


I should point out that if you are doing this as part of some licensing or "intellectual property management" scheme, you are probably wasting your time. Any practical scheme that you care to implement in client-side code (i.e. code that runs on the user's machine) can be broken ... unless the machine is totally locked down.



来源:https://stackoverflow.com/questions/17872180/load-classes-from-a-jar-file-from-a-url-to-memory-and-then-run-the-main-class-ou

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