这有点骇人听闻,但是他做了他的工作,这段代码基本上创建了一个伪造的url方案(myjarprotocol),当打开该方案时,它会返回该
jarBytes字段(您的实际jar数据所在的位置)。然后通过反射它调用
SystemClassLoader.addURL以URL作为他必须加载的jar参数。总之,SystemClassLoader被欺骗从伪造的url方案加载jar,该url方案返回您想要的任何InputStream。
public class JarLoader { private static final byte[] jarBytes = new byte[] { 0x00 }; public static void main(String[] args) throws Exception { URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { public URLStreamHandler createURLStreamHandler(String urlProtocol) { System.out.println("Someone asked for protocol: " + urlProtocol); if ("myjarprotocol".equalsIgnoreCase(urlProtocol)) { return new URLStreamHandler() { @Override protected URLConnection openConnection(URL url) throws IOException { return new URLConnection(url) { public void connect() throws IOException {} public InputStream getInputStream() throws IOException { System.out.println("Someone is getting my jar!!"); return new ByteArrayInputStream(jarBytes); } }; } }; } return null; } }); System.out.println("Loading jar with fake protocol!"); loadJarFromURL(new URL("myjarprotocol:fakeparameter")); } public static final void loadJarFromURL(URL jarURL) throws Exception { URLClassLoader systemClassloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method systemClassloaderMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); systemClassloaderMethod.setAccessible(true); systemClassloaderMethod.invoke(systemClassloader, jarURL); // This make classloader open the connection systemClassloader.findResource("/resource-404"); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)