简体   繁体   English

Java:jar字节数组到实例化对象

[英]Java: Jar Byte Array to Instantiated Object

I have an byte array of a jar file and I want to instantiate an object defined by a class contained in the jar. 我有一个jar文件的字节数组,我想实例化一个由jar中包含的类定义的对象。 How to I do this? 我该怎么做? Right now I am stuck at 现在我被困在

InputStream inputStream = App.class.getResourceAsStream("/example.jar");
byte[] bytes = IOUtils.toByteArray(inputStream);

I think I will need 2 things, a zip file reader and a class loader. 我想我需要两件事,一个zip文件阅读器和一个类加载器。 Does that sound like the right direction? 这听起来像是正确的方向吗?

You can use inbuilt URLClassLoader with the resource path you already have and instantiate the class. 您可以将内置的URLClassLoader与已经拥有的资源路径一起使用,并实例化该类。 You dont have to read the bytes yourself 您不必自己读取字节

// Create URLClassLoader 
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file://pathToJar/example.jar")});
Class<?> lookupClass = urlClassLoader.loadClass("com.somePackage.ClassName");
Object inst = lookupClass.newInstance();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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