java.net.URLClassLoader#newInstance ( )源码实例Demo

下面列出了java.net.URLClassLoader#newInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: commons-beanutils   文件: MemoryLeakTestCase.java
/**
 * Creates a new class loader instance.
 */
private static URLClassLoader newClassLoader() throws MalformedURLException {

    final String dataFilePath = MemoryLeakTestCase.class.getResource("pojotests").getFile();
    //System.out.println("dataFilePath: " + dataFilePath);
    final String location = "file://" + dataFilePath.substring(0,dataFilePath.length()-"org.apache.commons.beanutils2.memoryleaktests.pojotests".length());
    //System.out.println("location: " + location);

    final StringBuilder newString = new StringBuilder();
    for (int i=0;i<location.length();i++) {
        if (location.charAt(i)=='\\') {
            newString.append("/");
        } else {
            newString.append(location.charAt(i));
        }
    }
    final String classLocation = newString.toString();
    //System.out.println("classlocation: " + classLocation);

    final URLClassLoader theLoader = URLClassLoader.newInstance(new URL[]{new URL(classLocation)},null);
    return theLoader;
}
 
源代码2 项目: carbon-commons   文件: Java2WSDL.java
/**
 * This is the fall though method for wsdlview. This will check for required resources.
 *
 * @param options options array
 * @param uuids   uuid array
 * @return String id
 * @throws AxisFault will be thrown.
 */
public String java2wsdlWithResources(String[] options, String[] uuids) throws AxisFault {

    ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
    try {
        URL[] urls = new URL[uuids.length];
        for (int i = 0; i < uuids.length; i++) {
            urls[i] = new File(uuids[i]).toURL();
        }
        ClassLoader newCl = URLClassLoader.newInstance(urls, prevCl);
        Thread.currentThread().setContextClassLoader(newCl);
        return java2wsdl(options);
    } catch (MalformedURLException e) {
        throw AxisFault.makeFault(e);
    } finally {
        Thread.currentThread().setContextClassLoader(prevCl);
    }

}
 
源代码3 项目: styx   文件: BuildVsRuntimeJarAccessTest.java
@Test
public void pluginAndDependencyClassesAreAvailableWhenReferencingDirectory() throws IOException, ClassNotFoundException {
    Path jarLocation = createTemporarySharedDirectoryForJars();

    URL[] urls = list(jarLocation)
            .map(BuildVsRuntimeJarAccessTest::url)
            .toArray(URL[]::new);

    try (URLClassLoader classLoader = URLClassLoader.newInstance(urls)) {
        Class<?> pluginClass = classLoader.loadClass("testgrp.TestPlugin");
        assertThat(pluginClass.getName(), is("testgrp.TestPlugin"));

        Class<?> dependencyClass = classLoader.loadClass("depend.ExampleDependency");
        assertThat(dependencyClass.getName(), is("depend.ExampleDependency"));
    }
}
 
源代码4 项目: jdk8u-jdk   文件: VersionHelper12.java
ClassLoader getURLClassLoader(String[] url)
    throws MalformedURLException {
        ClassLoader parent = getContextClassLoader();
        /*
         * Classes may only be loaded from an arbitrary URL code base when
         * the system property com.sun.jndi.ldap.object.trustURLCodebase
         * has been set to "true".
         */
        if (url != null && "true".equalsIgnoreCase(trustURLCodebase)) {
            return URLClassLoader.newInstance(getUrlArray(url), parent);
        } else {
            return parent;
        }
}
 
源代码5 项目: openjdk-jdk9   文件: RuntimeTest.java
private static void testURLClassLoaderURL(URL jarURL,
        int mainVersionExpected, int helperVersionExpected,
        int resourceVersionExpected) throws ClassNotFoundException,
        NoSuchMethodException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException, IOException {
    System.out.println(
            "Testing URLClassLoader MV JAR support for URL: " + jarURL);
    URL[] urls = { jarURL };
    int mainVersionActual;
    int helperVersionActual;
    int resourceVersionActual;
    try (URLClassLoader cl = URLClassLoader.newInstance(urls)) {
        Class c = cl.loadClass("testpackage.Main");
        Method getMainVersion = c.getMethod("getMainVersion");
        mainVersionActual = (int) getMainVersion.invoke(null);
        Method getHelperVersion = c.getMethod("getHelperVersion");
        helperVersionActual = (int) getHelperVersion.invoke(null);
        try (InputStream ris = cl.getResourceAsStream("versionResource");
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(ris))) {
            resourceVersionActual = Integer.parseInt(br.readLine());
        }
    }

    assertEquals(mainVersionActual, mainVersionExpected,
                     "Test failed: Expected Main class version: "
                     + mainVersionExpected + " Actual version: "
                     + mainVersionActual);
    assertEquals(helperVersionActual, helperVersionExpected,
                     "Test failed: Expected Helper class version: "
                     + helperVersionExpected + " Actual version: "
                     + helperVersionActual);
    assertEquals(resourceVersionActual, resourceVersionExpected,
                     "Test failed: Expected resource version: "
                     + resourceVersionExpected + " Actual version: "
                     + resourceVersionActual);
}
 
源代码6 项目: jdk8u-jdk   文件: VersionHelper12.java
/**
 * @param className A non-null fully qualified class name.
 * @param codebase A non-null, space-separated list of URL strings.
 */
public Class<?> loadClass(String className, String codebase)
        throws ClassNotFoundException, MalformedURLException {

    ClassLoader parent = getContextClassLoader();
    ClassLoader cl =
             URLClassLoader.newInstance(getUrlArray(codebase), parent);

    return loadClass(className, cl);
}
 
@BeforeTest(groups = {"deserializationTest"})
public void prepare() throws Exception {
  Path tempPath = Files.createTempDirectory("generated");
  tempDir = tempPath.toFile();

  classLoader = URLClassLoader.newInstance(new URL[]{tempDir.toURI().toURL()},
      FastSpecificDeserializerGeneratorTest.class.getClassLoader());
}
 
源代码8 项目: awesomesauce-rfduino   文件: SamsungBleStack.java
/** Function to use our version of BluetoothAdapter and BluetoothDevice if the native Android OS doesn't have 4.3 yet. 
 * @throws IOException 
 * @throws ClassNotFoundException **/
public static void loadSamsungLibraries(Context hostActivityContext) throws IOException, ClassNotFoundException{
	File internalStoragePath = hostActivityContext.getFileStreamPath("com.samsung.ble.sdk-1.0.jar");
	if (!internalStoragePath.exists()){
		
	
	  //We'll copy the SDK to disk so we can open the JAR file:
	  // it has to be first copied from asset resource to a storage location.
	  InputStream jar = hostActivityContext.getAssets().open("com.samsung.ble.sdk-1.0.jar", Context.MODE_PRIVATE);
	  FileOutputStream outputStream = hostActivityContext.openFileOutput("com.samsung.ble.sdk-1.0.jar", Context.MODE_PRIVATE);
	     
	  int size = 0;
	    // Read the entire resource into a local byte buffer.
	    byte[] buffer = new byte[1024];
	    while((size=jar.read(buffer,0,1024))>=0){
	      outputStream.write(buffer,0,size);
	    }
	    jar.close();
	   
	}
	    
	  Log.i(logTag, internalStoragePath.getAbsolutePath()+" exists? "+ internalStoragePath.exists());
	  
         URL[] urls = { new URL("jar:file:" + internalStoragePath.getAbsolutePath()+"!/") };
         URLClassLoader cl  = URLClassLoader.newInstance(urls);
         
         samsungBluetoothAdapterClass = cl.loadClass("android.bluetooth.BluetoothAdapter");
         samsungBluetoothDeviceClass = cl.loadClass("android.bluetooth.BluetoothDevice");
 	
}
 
源代码9 项目: FridaAndroidTracer   文件: FridaAndroidTracer.java
private ClassLoader loadJars(String[] jarFiles) {
    URL[] urls = Stream.of(jarFiles)
            .map(name -> {
                try {
                    return new File(name).toURI().toURL();
                } catch (MalformedURLException e) {
                    System.out.println("Fail to load jar file: " + name);
                    e.printStackTrace();
                    return null;
                }
            })
            .toArray(URL[]::new);
    return URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
}
 
源代码10 项目: buffer_bci   文件: ResourceBundleWrapper.java
/**
 * Instantiate a {@link URLClassLoader} for resource lookups where the
 * codeBase URL is removed.  This method is typically called from an
 * applet's init() method.  If this method is never called, the
 * <code>getBundle()</code> methods map to the standard
 * {@link ResourceBundle} lookup methods.
 *
 * @param codeBase  the codeBase URL.
 * @param urlClassLoader  the class loader.
 */
public static void removeCodeBase(URL codeBase,
        URLClassLoader urlClassLoader) {
    List urlsNoBase = new ArrayList();

    URL[] urls = urlClassLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (!urls[i].sameFile(codeBase)) {
            urlsNoBase.add(urls[i]);
        }
    }
    // substitute the filtered URL list
    URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]);
    noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);
}
 
源代码11 项目: jdk8u60   文件: VersionHelper12.java
/**
 * @param className A non-null fully qualified class name.
 * @param codebase A non-null, space-separated list of URL strings.
 */
public Class<?> loadClass(String className, String codebase)
        throws ClassNotFoundException, MalformedURLException {

    ClassLoader parent = getContextClassLoader();
    ClassLoader cl =
             URLClassLoader.newInstance(getUrlArray(codebase), parent);

    return loadClass(className, cl);
}
 
源代码12 项目: jdk8u_jdk   文件: VersionHelper12.java
ClassLoader getURLClassLoader(String[] url)
    throws MalformedURLException {
        ClassLoader parent = getContextClassLoader();
        /*
         * Classes may only be loaded from an arbitrary URL code base when
         * the system property com.sun.jndi.ldap.object.trustURLCodebase
         * has been set to "true".
         */
        if (url != null && "true".equalsIgnoreCase(trustURLCodebase)) {
            return URLClassLoader.newInstance(getUrlArray(url), parent);
        } else {
            return parent;
        }
}
 
源代码13 项目: avro-util   文件: FastDeserializerDefaultsTest.java
@BeforeTest(groups = {"deserializationTest"})
public void prepare() throws Exception {
  Path tempPath = Files.createTempDirectory("generated");
  tempDir = tempPath.toFile();

  classLoader = URLClassLoader.newInstance(new URL[]{tempDir.toURI().toURL()},
      FastDeserializerDefaultsTest.class.getClassLoader());
}
 
@BeforeTest(groups = {"serializationTest"})
public void prepare() throws Exception {
  tempDir = getCodeGenDirectory();

  classLoader = URLClassLoader.newInstance(new URL[]{tempDir.toURI().toURL()},
      FastGenericSerializerGeneratorTest.class.getClassLoader());
}
 
源代码15 项目: openjdk-jdk9   文件: JaxbMarshallTest.java
@Test
public void marshallClassCastExceptionTest() throws Exception {
    JAXBContext jaxbContext;
    Marshaller marshaller;
    URLClassLoader jaxbContextClassLoader;
    // Generate java classes by xjc
    runXjc(XSD_FILENAME);
    // Compile xjc generated java files
    compileXjcGeneratedClasses();

    // Create JAXB context based on xjc generated package.
    // Need to create URL class loader ot make compiled classes discoverable
    // by JAXB context
    jaxbContextClassLoader = URLClassLoader.newInstance(new URL[] {testWorkDirUrl});
    jaxbContext = JAXBContext.newInstance( TEST_PACKAGE, jaxbContextClassLoader);

    // Create instance of Xjc generated data type.
    // Java classes were compiled during the test execution hence reflection
    // is needed here
    Class classLongListClass = jaxbContextClassLoader.loadClass(TEST_CLASS);
    Object objectLongListClass = classLongListClass.newInstance();
    // Get 'getIn' method object
    Method getInMethod = classLongListClass.getMethod( GET_LIST_METHOD, (Class [])null );
    // Invoke 'getIn' method
    List<Long> inList = (List<Long>)getInMethod.invoke(objectLongListClass);
    // Add values into the jaxb object list
    inList.add(Long.valueOf(0));
    inList.add(Long.valueOf(43));
    inList.add(Long.valueOf(1000000123));

    // Marshall constructed complex type variable to standard output.
    // In case of failure the ClassCastException will be thrown
    marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(objectLongListClass, System.out);
}
 
源代码16 项目: jAudioGIT   文件: FeatureListHandler.java
public void characters(char[] ch, int start, int length)
			throws SAXException {
		switch (tagType) {
		case FEATURE_LIST:
			break;
		case FEATURE:
			break;
		case CLASS:
			className = new String(ch, start, length);
			break;
		case ON:
			break;
		case PLUGIN_LOCATION:
			try {
					URL[] pluginURL = new URL[]{new URL(new String(ch,start,length))};
					classLoader =URLClassLoader.newInstance(pluginURL, Thread.currentThread().getContextClassLoader());
//					java.lang.Thread.currentThread().setContextClassLoader(classLoader);
				} catch (MalformedURLException e) {
					throw new SAXException("Plugin location not a valid URL:"+new String(ch,start,length));
				}
				break;
		case AGGREGATOR:
			className = new String(ch,start,length);
			break;
		default:
			if(!firstTag){
				throw new SAXException("Unknown tagType found (" + tagType + ") - content='"+new String(ch,start,length)+"'");
			}
		}
	}
 
/**
 * 获取目标目录的ClassLoader
 * @return
 */
public ClassLoader getTargetClassLoader() throws MalformedURLException {
    return URLClassLoader.newInstance(new URL[]{
            new File(targetProject).toURI().toURL()
    });
}
 
源代码18 项目: flink   文件: PojoSerializerUpgradeTest.java
private void testPojoSerializerUpgrade(String classSourceA, String classSourceB, boolean hasBField, boolean isKeyedState) throws Exception {
	final Configuration taskConfiguration = new Configuration();
	final ExecutionConfig executionConfig = new ExecutionConfig();
	final KeySelector<Long, Long> keySelector = new IdentityKeySelector<>();
	final Collection<Long> inputs = Arrays.asList(1L, 2L, 45L, 67L, 1337L);

	// run the program with classSourceA
	File rootPath = temporaryFolder.newFolder();
	File sourceFile = writeSourceFile(rootPath, POJO_NAME + ".java", classSourceA);
	compileClass(sourceFile);

	final ClassLoader classLoader = URLClassLoader.newInstance(
		new URL[]{rootPath.toURI().toURL()},
		Thread.currentThread().getContextClassLoader());

	OperatorSubtaskState stateHandles = runOperator(
		taskConfiguration,
		executionConfig,
		new StreamMap<>(new StatefulMapper(isKeyedState, false, hasBField)),
		keySelector,
		isKeyedState,
		stateBackend,
		classLoader,
		null,
		inputs);

	// run the program with classSourceB
	rootPath = temporaryFolder.newFolder();

	sourceFile = writeSourceFile(rootPath, POJO_NAME + ".java", classSourceB);
	compileClass(sourceFile);

	final ClassLoader classLoaderB = URLClassLoader.newInstance(
		new URL[]{rootPath.toURI().toURL()},
		Thread.currentThread().getContextClassLoader());

	runOperator(
		taskConfiguration,
		executionConfig,
		new StreamMap<>(new StatefulMapper(isKeyedState, true, hasBField)),
		keySelector,
		isKeyedState,
		stateBackend,
		classLoaderB,
		stateHandles,
		inputs);
}
 
源代码19 项目: yGuard   文件: DefaultMethodTest.java
@Test
public void SimpleChainTest() {
  final String testTypeName = "com.yworks.yshrink.java13.SimpleChainTest";

  final String fileName = "SimpleChainTest.txt";
  final URL source = getClass().getResource(fileName);
  assertNotNull("Could not resolve " + fileName + '.', source);


  // compile the java source code
  final com.yworks.util.Compiler compiler = com.yworks.util.Compiler.newCompiler();

  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  compiler.compile(List.of(compiler.newUrlSource(testTypeName, source)), baos);

  try {
    // store resulting bytecode in temporary files and ...
    File inTmp = File.createTempFile(name.getMethodName() + "_in_", ".jar");
    File outTmp = File.createTempFile(name.getMethodName() + "_out_", ".jar");
    Files.write(inTmp.toPath(), baos.toByteArray());

    // Run shrinker
    YShrink yShrink = new YShrink(false, "SHA-1,MD5");
    InOutPair inOutPair = new InOutPair();
    inOutPair.setIn(inTmp);
    inOutPair.setOut(outTmp);
    yShrink.doShrinkPairs(List.of(inOutPair), new AllMainMethodsFilter(), null);

    //   load shrinked class and run test method
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    final ClassLoader cl = URLClassLoader.newInstance(new URL[]{outTmp.toURI().toURL()});
    final Class shrinkedType = Class.forName(testTypeName, true, cl);
    final Method run =  shrinkedType.getMethod("run", PrintStream.class);
    run.invoke(null, new PrintStream(output));

    //   check test method output
    assertEquals(
            "Wrong test output",
            String.format("Hello from second interface%n", System.lineSeparator()),
            output.toString());

    // clean up and remove temporary files
    inTmp.delete();
    outTmp.delete();
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
源代码20 项目: coroutines   文件: TestUtils.java
/**
 * Writes entries to a JAR and loads it up.
 * @param entries class nodes to put in to jar
 * @return class loader with files in newly created JAR available
 * @throws IOException if any IO error occurs
 * @throws NullPointerException if any argument is {@code null} or contains {@code null}
 * @throws IllegalArgumentException if {@code classNodes} is empty
 */
public static URLClassLoader createJarAndLoad(JarEntry ... entries) throws IOException {
    Validate.notNull(entries);
    Validate.noNullElements(entries);
    
    File jarFile = createJar(entries);
    return URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() }, TestUtils.class.getClassLoader());
}