下面列出了java.net.URLClassLoader#newInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
/**
* 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);
}
}
@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"));
}
}
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;
}
}
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);
}
/**
* @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());
}
/** 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");
}
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());
}
/**
* 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);
}
/**
* @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);
}
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;
}
}
@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());
}
@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);
}
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()
});
}
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);
}
@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();
}
}
/**
* 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());
}