简体   繁体   中英

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. 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. Does that sound like the right direction?

You can use inbuilt URLClassLoader with the resource path you already have and instantiate the class. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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