@Test(expected = ClassFormatError.class) @Ignore( "Surefire considered LoadableTestJob.class a test in the wrong location, and failed the build") public void testDefineClass() throws Exception { ByteClassLoader loader = new ByteClassLoader(new File(TestInfo.WORKING_DIR, "LoadableTestJob.class")); Class<LoadableTestJob> c = loader.defineClass(); assertEquals( "Class name should be correct", "dk.netarkivet.common.utils.batch.LoadableTestJob", c.getName()); // Note that we can't cast it to a LoadableTestJob, as we've already // loaded that class through a different classloader, so they aren't // quite the same. FileBatchJob job = c.newInstance(); loader = new ByteClassLoader(TestInfo.INPUT_1); c = loader.defineClass(); fail("Should have died trying to load illegal class"); }
/** * Method for initializing the loaded batchjob. * * @throws IOFailure If the batchjob cannot be loaded. */ protected void loadBatchJob() throws IOFailure { ByteClassLoader singleClassLoader = new ByteClassLoader(fileContents); try { Class batchClass = singleClassLoader.defineClass(); if (args.size() == 0) { loadedJob = (FileBatchJob) batchClass.newInstance(); } else { // get argument classes (string only). Class[] argClasses = new Class[args.size()]; for (int i = 0; i < args.size(); i++) { argClasses[i] = String.class; } // extract the constructor and instantiate the batchjob. Constructor con = batchClass.getConstructor(argClasses); loadedJob = (FileBatchJob) con.newInstance(args.toArray()); log.debug("Loaded batchjob with arguments: '" + args + "'."); } } catch (InvocationTargetException e) { final String msg = "Not allowed to invoke the batchjob '" + fileName + "'."; log.warn(msg, e); throw new IOFailure(msg, e); } catch (NoSuchMethodException e) { final String msg = "No constructor for the arguments '" + args + "' can be found for the batchjob '" + fileName + "'."; log.warn(msg, e); throw new IOFailure(msg, e); } catch (InstantiationException e) { String errMsg = "Cannot instantiate batchjob from byte array"; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } catch (IllegalAccessException e) { String errMsg = "Cannot access loaded job from byte array"; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } }