public static File buildJar(String testDir, String className, String code, String folder)
    throws Exception {
    String javaCode = code != null ? code : "public class " + className + " {}";
    Path srcDir = new Path(testDir, "src");
    File srcDirPath = new File(srcDir.toString());
    srcDirPath.mkdirs();
    File sourceCodeFile = new File(srcDir.toString(), className + ".java");
    BufferedWriter bw = Files.newBufferedWriter(sourceCodeFile.toPath(), StandardCharsets.UTF_8);
    bw.write(javaCode);
    bw.close();

    // compile it by JavaCompiler
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> cu = fm.getJavaFileObjects(sourceCodeFile);
    List<String> options = new ArrayList<>(2);
    options.add("-classpath");
    // only add hbase classes to classpath. This is a little bit tricky: assume
    // the classpath is {hbaseSrc}/target/classes.
    String currentDir = new File(".").getAbsolutePath();
    String classpath = currentDir + File.separator + "target" + File.separator + "classes"
      + System.getProperty("path.separator") + System.getProperty("java.class.path")
      + System.getProperty("path.separator") + System.getProperty("surefire.test.class.path");

    options.add(classpath);
    LOG.debug("Setting classpath to: " + classpath);

    JavaCompiler.CompilationTask task = compiler.getTask(null, fm, null, options, null, cu);
    assertTrue("Compile file " + sourceCodeFile + " failed.", task.call());

    // build a jar file by the classes files
    String jarFileName = className + ".jar";
    File jarFile = new File(folder, jarFileName);
    jarFile.getParentFile().mkdirs();
    if (
      !createJarArchive(jarFile, new File[] { new File(srcDir.toString(), className + ".class") })
    ) {
      fail("Build jar file failed.");
    }
    return jarFile;
  }
Create a test jar for testing purpose for a given class name with specified code string.
@param testDir   the folder under which to store the test class
@param className the test class name
@param code      the optional test class code, which can be null. If null, an empty class will
                 be used
@param folder    the folder under which to store the generated jar
@return the test jar file generated
hbase-common/src/test/java/org/apache/hadoop/hbase/util/ClassLoaderTestHelper.java