Skip to content
mguymon edited this page Sep 28, 2012 · 6 revisions

Isolated ClassLoader

LockJar is able to populate a custom ClassLoader and create Java instances from the custom ClassLoader using LockJar::ClassLoader. The key is calling LockJar::ClassLoader's new_instance instead of directly calling new to create a Java Object. The call to new_instance uses the custom ClassLoader to create the Java Object.

Example of using LockJar::ClassLoader#isolate

# Manually generate the IsolateJarfile.lock 
LockJar.lock( :lockfile => 'tmp/IsolateJarfile.lock' ) do
  jar 'com.fasterxml.jackson.core:jackson-core:2.0.6'
  jar 'com.fasterxml.jackson.core:jackson-databind:2.0.6'
end
  
json = '{ "test1": "1test1", "test2": "2test2"}'
  
# Create class loader using lockfile
class_loader = LockJar::ClassLoader.new( 'tmp/IsolateJarfile.lock' )

# Convert json string to a Hash using Jackson
map = class_loader.isolate do
  # create new instance of JsonFactory by LockJar::ClassLoader's new_instance
  factory = new_instance( 'com.fasterxml.jackson.core.JsonFactory' )

  # create new instance of ObjectMapper by LockJar::ClassLoader's new_instance
  mapper = new_instance( 'com.fasterxml.jackson.databind.ObjectMapper', factory)

  mapper.readValue(json, java.util.Map.java_class)
end
Clone this wiki locally