下面列出了java.net.URLClassLoader#loadClass ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private long sameInstanceReflectionConstructorResolution(int spins) throws Exception {
Class<?>[] classes = new Class[spins];
for (int i = 0; i < spins; i++) {
URLClassLoader loader = new URLClassLoader(new URL[]{ classpathDirectory.toURI().toURL() });
classes[i] = loader.loadClass(targetClassName);
loader.close();
}
long start = System.nanoTime();
for (int i = 0; i < spins; i++) {
classes[i].getConstructor(String.class, Object.class, Character.class, Float[].class);
}
long end = System.nanoTime();
return end - start;
}
private File deduceArkConfBaseDir() {
File arkConfDir = null;
try {
URLClassLoader tempClassLoader = new URLClassLoader(urls);
Class entryClass = tempClassLoader.loadClass(className);
String classLocation = ClassUtils.getCodeBase(entryClass);
File file = classLocation == null ? null : new File(classLocation);
while (file != null) {
arkConfDir = new File(file.getPath() + File.separator + ARK_CONF_BASE_DIR);
if (arkConfDir.exists() && arkConfDir.isDirectory()) {
break;
}
file = file.getParentFile();
}
} catch (Throwable throwable) {
throw new ArkRuntimeException(throwable);
}
// return 'conf/' directory or null
return arkConfDir == null ? null : arkConfDir.getParentFile();
}
public static void main(String[] args) throws Exception {
File file = new File(BASE);
URL[] urls = new URL[1];
urls[0] = file.toURI().toURL();
URLClassLoader ucl = new URLClassLoader(urls);
Class<?> c = ucl.loadClass("MyTransform");
Constructor<?> cons = c.getConstructor(new Class[] {});
Object o = cons.newInstance();
// Apache code swallows the ClassNotFoundExc, so we need to
// check if the Transform has already been registered by registering
// it again and catching an AlgorithmAlreadyRegisteredExc
try {
Transform.register(MyTransform.URI, "MyTransform");
throw new Exception("ClassLoaderTest failed");
} catch (AlgorithmAlreadyRegisteredException e) {
// test passed
}
}
@Test
public void testServiceLoaderWithoutExclusion() throws Exception {
URLClassLoader parent = new URLClassLoader(new URL[]{parentJarURL}, this.getClass().getClassLoader());
parent.loadClass("org.jboss.as.model.test.parent.WelcomeParent");
ChildFirstClassLoader child = new ChildFirstClassLoader(parent, new HashSet<Pattern>(), new HashSet<Pattern>(), null, null, new URL[]{childJarURL});
Class<?> welcomeParent = child.loadClass("org.jboss.as.model.test.parent.WelcomeParent");
Class<?> welcomeChild = child.loadClass("org.jboss.as.model.test.child.WelcomeChild");
Class<?> welcome = this.getClass().getClassLoader().loadClass("org.jboss.as.model.test.api.Welcome");
ServiceLoader loader = ServiceLoader.load(welcome, child);
int loaded = 0;
Set<Class<?>> impls = new HashSet<>(Arrays.asList(welcomeParent, welcomeChild));
for (Object svc : loader) {
impls.remove(svc.getClass());
loaded++;
}
Assert.assertTrue(impls.toString(), impls.isEmpty());
Assert.assertEquals(2, loaded);
}
@Override
public Map<SourceLocation, List<TestResult>> getTestListPerStatement() {
SpoonedProject spooner = new SpoonedProject(nopolContext.getProjectSources(), nopolContext);
final List<SourcePosition> l = new ArrayList<>();
spooner.process(new AbstractProcessor<CtIf>(){
@Override
public void process(CtIf ctIf) {
l.add(ctIf.getCondition().getPosition());
}
});
Map<SourceLocation, List<TestResult>> countPerSourceLocation = new HashMap<>();
List<TestResult> res = new ArrayList<>();
for (String testClass : nopolContext.getProjectTests()) {
try {
URLClassLoader urlClassLoader = new URLClassLoader(nopolContext.getProjectClasspath(), this.getClass().getClassLoader());
Class klass = urlClassLoader.loadClass(testClass);
// does not work, see https://stackoverflow.com/a/29865611
//for (FrameworkMethod desc : new BlockJUnit4ClassRunner(klass).getChildren()) {
// so we get the methods ourselves
// only support basic Junit4
for (String m : getTestMethods(klass)) {
res.add(new TestResultImpl(TestCase.from(m), false));
}
} catch (Exception e) {
System.out.println(testClass);
}
}
for(SourcePosition pos : l) {
SourceLocation loc = new SourceLocation(pos.getCompilationUnit().getMainType().getQualifiedName(), pos.getLine());
countPerSourceLocation.put(loc, Collections.unmodifiableList(res));
}
return countPerSourceLocation;
}
static boolean klassLoader(URL baseURL,
String resource,
boolean expectToFind,
boolean expectbDotJar,
boolean expectcDotJar) throws IOException {
debug("----------------------------------");
debug("Running test looking for " + resource);
URLClassLoader loader = getLoader(baseURL);
httpServer.reset();
Class<?> ADotAKlass = null;
try {
ADotAKlass = loader.loadClass("a.A");
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
throw new RuntimeException("Error in test: " + cnfe);
}
URL u = ADotAKlass.getResource(resource);
if (expectToFind && u == null) {
System.out.println("Expected to find " + resource + " but didn't");
return false;
}
debug("HttpServer: " + httpServer);
if (!expectbDotJar && httpServer.bDotJar > 0) {
debug("Unexpeced request sent to the httpserver for b.jar");
return false;
}
if (!expectcDotJar && httpServer.cDotJar > 0) {
debug("Unexpeced request sent to the httpserver for c.jar");
return false;
}
return true;
}
protected void registerPluginJars() throws KettlePluginException {
List<JarFileAnnotationPlugin> jarFilePlugins = findAnnotatedClassFiles( pluginClass.getName() );
for ( JarFileAnnotationPlugin jarFilePlugin : jarFilePlugins ) {
URLClassLoader urlClassLoader =
createUrlClassLoader( jarFilePlugin.getJarFile(), getClass().getClassLoader() );
try {
Class<?> clazz = urlClassLoader.loadClass( jarFilePlugin.getClassName() );
if ( clazz == null ) {
throw new KettlePluginException( "Unable to load class: " + jarFilePlugin.getClassName() );
}
List<String> libraries = Arrays.stream( urlClassLoader.getURLs() )
.map( URL::getFile )
.collect( Collectors.toList() );
Annotation annotation = clazz.getAnnotation( pluginClass );
handlePluginAnnotation( clazz, annotation, libraries, false, jarFilePlugin.getPluginFolder() );
} catch ( Exception e ) {
// Ignore for now, don't know if it's even possible.
LogChannel.GENERAL.logError(
"Unexpected error registering jar plugin file: " + jarFilePlugin.getJarFile(), e );
} finally {
if ( urlClassLoader instanceof KettleURLClassLoader ) {
( (KettleURLClassLoader) urlClassLoader ).closeClassLoader();
}
}
}
}
/**
* Load the class with a certain name using the class loader of certain plugin.
*
* @param plugin The plugin for which we want to use the class loader
* @param className The name of the class to load
* @return the name of the class
* @throws HopPluginException In case there is something wrong
*/
@SuppressWarnings( "unchecked" )
public <T> T getClass( IPlugin plugin, String className ) throws HopPluginException {
try {
if ( plugin.isNativePlugin() ) {
return (T) Class.forName( className );
} else if ( ( plugin instanceof IClassLoadingPlugin ) && ( (IClassLoadingPlugin) plugin ).getClassLoader() != null ) {
return (T) ( (IClassLoadingPlugin) plugin ).getClassLoader().loadClass( className );
} else {
URLClassLoader ucl;
lock.writeLock().lock();
try {
Map<IPlugin, URLClassLoader> classLoaders = classLoaderMap.computeIfAbsent( plugin.getPluginType(), k -> new HashMap<>() );
ucl = classLoaders.get( plugin );
if ( ucl == null ) {
if ( !Utils.isEmpty( plugin.getClassLoaderGroup() ) ) {
ucl = classLoaderGroupsMap.get( plugin.getClassLoaderGroup() );
} else {
ucl = folderBasedClassLoaderMap.get( plugin.getPluginDirectory().toString() );
}
}
if ( ucl != null ) {
classLoaders.put( plugin, ucl ); // save for later use...
}
} finally {
lock.writeLock().unlock();
}
if ( ucl == null ) {
throw new HopPluginException( "Unable to find class loader for plugin: " + plugin );
}
return (T) ucl.loadClass( className );
}
} catch ( Exception e ) {
throw new HopPluginException( "Unexpected error loading class with name: " + className, e );
}
}
/**
* 加载该服务所有的jar,并实例化jar中所有服务的实现
*
* @param services
* @throws MalformedURLException
*/
private static void initService(Map<String, String> services, String serviceLibPath) throws Exception {
File serviceLibDir = new File(serviceLibPath);
File[] jarFiles = serviceLibDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
URL[] jarURLS = new URL[jarFiles.length];
for (int i = 0; i < jarFiles.length; i++) {
log.info("加载的类有:" + jarFiles[i].getName());
jarURLS[i] = jarFiles[i].toURI().toURL();
}
URLClassLoader classLoader = new URLClassLoader(jarURLS, ClassLoader.getSystemClassLoader());
/**
* 懒加载模式,在启动服务时,初始化所有实现类
*/
Map<String, Object> instances = new HashMap<String, Object>();
Map<String, Class> types = new HashMap<String, Class>();
Iterator<Entry<String, String>> it = services.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
Class clazz = classLoader.loadClass(e.getValue());
instances.put(e.getKey(), clazz.newInstance());
types.put(e.getKey(), clazz);
}
Global.getInstance().setClassLoader(classLoader);
Global.getInstance().setServiceImpl(instances);
Global.getInstance().setServiceClass(types);
}
/**
* 获取源码目录下指定包下的类
* @param root
* @param pkg
* @return
* @throws Exception
*/
public static List<Class<?>> getClassInfo(String root,String pkg) throws Exception
{
List<Class<?>> list=new ArrayList<Class<?>>();
String suffix=".java";
File rootDir=new File(root);
Set<File> files=FileUtil.findFileByDirAndSub(rootDir, new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.getName().endsWith(suffix);
}
});
URLClassLoader loader=new URLClassLoader(new URL[]{rootDir.toURI().toURL()});
try {
// 获取路径长度
int clazzPathLen = rootDir.getAbsolutePath().length() + 1;
for(File file:files)
{
String className = file.getAbsolutePath();
className = className.substring(clazzPathLen, className.length() - suffix.length());
className = className.replace(File.separatorChar, '.');
try {
Class<?> clazz=loader.loadClass(className);
String pkgName=clazz.getPackage().getName();
if(pkgName.startsWith(pkg))
{
list.add(clazz);
}
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
} finally {
loader.close();
}
return list;
}
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder(256);
sb.append("file:");
sb.append(System.getProperty("test.src", "."));
sb.append(File.separatorChar);
sb.append("test.jar");
URL[] url = {new URL(sb.toString())};
URLClassLoader cl = new URLClassLoader(url);
Class type = cl.loadClass("test.Test");
if (type == null) {
throw new Error("could not find class test.Test");
}
InputStream stream = new ByteArrayInputStream(DATA.getBytes());
ExceptionListener el = new ExceptionListener() {
public void exceptionThrown(Exception exception) {
throw new Error("unexpected exception", exception);
}
};
XMLDecoder decoder = new XMLDecoder(stream, null, el, cl);
Object object = decoder.readObject();
decoder.close();
if (!type.equals(object.getClass())) {
throw new Error("unexpected " + object.getClass());
}
}
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder(256);
sb.append("file:");
sb.append(System.getProperty("test.src", "."));
sb.append(File.separatorChar);
sb.append("test.jar");
URL[] url = {new URL(sb.toString())};
URLClassLoader cl = new URLClassLoader(url);
Class type = cl.loadClass("test.Test");
if (type == null) {
throw new Error("could not find class test.Test");
}
InputStream stream = new ByteArrayInputStream(DATA.getBytes());
ExceptionListener el = new ExceptionListener() {
public void exceptionThrown(Exception exception) {
throw new Error("unexpected exception", exception);
}
};
XMLDecoder decoder = new XMLDecoder(stream, null, el, cl);
Object object = decoder.readObject();
decoder.close();
if (!type.equals(object.getClass())) {
throw new Error("unexpected " + object.getClass());
}
}
public void testEquals_classloader_equal() throws Exception {
ClassLoader cl = ColorEnum.class.getClassLoader();
if (cl instanceof URLClassLoader) {
URLClassLoader urlCL = (URLClassLoader) cl;
URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null);
URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null);
Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ColorEnum");
Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ColorEnum");
Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null);
Object blue2 = otherEnumClass2.getDeclaredField("BLUE").get(null);
assertEquals(true, blue1.equals(blue2));
}
}
private static List<Class<?>> checkJarFile(String jf, String[] pkgs)
throws IOException {
LOG.log(Level.INFO, "Finding Commands in {0}", jf);
List<Class<?>> classes = new ArrayList<>();
try (JarFile jarFile = new JarFile(jf)) {
Enumeration<JarEntry> entries = jarFile.entries();
URL[] urls = {new URL("jar:file:" + jf + "!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.endsWith(".class")) {
name = name.substring(0, name.length() - 6).replace('/', '.');
if (!inPkgs(pkgs, name)) {
try {
Class<?> c = cl.loadClass(name);
c.asSubclass(Command.class);
classes.add(c);
} catch (ClassNotFoundException ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
} catch (ClassCastException e) {
}
}
}
}
//need close if jars will be updated in runtime
// as in http://bugs.java.com/bugdatabase/view_bug.do?bug_id=5041014
cl.close();
}
return classes;
}
private void listClass(URLClassLoader loader, String className) throws ClassNotFoundException {
Class klass = loader.loadClass(className);
log.info("Listing class {}", klass);
listClass(klass);
}
@Test
public void test() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
JavaFileObject projectSource = JavaFileObjects.forResource("Project.java");
JavaFileObject userSource = JavaFileObjects.forResource("UserEntity.java");
JavaFileObject addressSource = JavaFileObjects.forResource("UserAddress.java");
JavaFileObject testSource = JavaFileObjects.forResource("TypedQuerySpecTest.java");
Compilation compilation = javac()
.withProcessors(new CrnkProcessor())
.compile(projectSource, userSource, addressSource, testSource);
assertThat(compilation).succeededWithoutWarnings();
ImmutableList<JavaFileObject> generatedFiles = compilation.generatedFiles();
Assert.assertEquals(3 + 3 + 9 + 1, generatedFiles.size());
URLClassLoader classLoader = toClassLoader(generatedFiles);
Class<?> testClass = classLoader.loadClass("test.TypedQuerySpecTest");
Object testObject = testClass.newInstance();
JavaFileObject sourceFile = compilation.generatedSourceFile("test.UserPathSpec").get();
LOGGER.debug(sourceFile.getCharContent(true).toString());
QuerySpec querySpec = (QuerySpec) testClass.getMethod("createQuerySpec").invoke(testObject);
FilterSpec filterSpec = (FilterSpec) testClass.getMethod("createFilterSpec").invoke(testObject);
SortSpec sortSpec = (SortSpec) testClass.getMethod("createSortSpec").invoke(testObject);
Assert.assertEquals(1, querySpec.getFilters().size());
Assert.assertEquals(1, querySpec.getSort().size());
Assert.assertEquals(1, querySpec.getIncludedFields().size());
Assert.assertEquals(1, querySpec.getIncludedRelations().size());
FilterSpec queryFilterSpec = querySpec.getFilters().get(0);
Assert.assertEquals(FilterOperator.EQ, queryFilterSpec.getOperator());
Assert.assertEquals("projects.id", queryFilterSpec.getPath().toString());
Assert.assertEquals((Integer) 12, queryFilterSpec.getValue());
SortSpec querySortSpec = querySpec.getSort().get(0);
Assert.assertEquals(Direction.DESC, querySortSpec.getDirection());
Assert.assertEquals("loginId", querySortSpec.getPath().toString());
Assert.assertEquals("projects", querySpec.getIncludedRelations().get(0).getPath().toString());
Assert.assertEquals("loginId", querySpec.getIncludedFields().get(0).getPath().toString());
Assert.assertEquals(FilterOperator.EQ, filterSpec.getOperator());
Assert.assertEquals("projects.id", filterSpec.getPath().toString());
Assert.assertEquals((Integer) 12, filterSpec.getValue());
Assert.assertEquals(Direction.DESC, sortSpec.getDirection());
Assert.assertEquals("projects.id", sortSpec.getPath().toString());
}
static boolean javaUtilServiceLoaderTest(URL baseURL,
String serviceClass,
boolean expectToFind,
boolean expectbDotJar,
boolean expectcDotJar) throws IOException {
debug("----------------------------------");
debug("Running test with java.util.ServiceLoader looking for " + serviceClass);
URLClassLoader loader = getLoader(baseURL);
httpServer.reset();
Class<?> messageServiceClass = null;
try {
messageServiceClass = loader.loadClass(serviceClass);
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
throw new RuntimeException("Error in test: " + cnfe);
}
Iterator<?> iterator = (ServiceLoader.load(messageServiceClass, loader)).iterator();
if (expectToFind && !iterator.hasNext()) {
debug(messageServiceClass + " NOT found.");
return false;
}
while (iterator.hasNext()) {
debug("found " + iterator.next() + " " + messageService);
}
debug("HttpServer: " + httpServer);
if (!expectbDotJar && httpServer.bDotJar > 0) {
debug("Unexpeced request sent to the httpserver for b.jar");
return false;
}
if (!expectcDotJar && httpServer.cDotJar > 0) {
debug("Unexpeced request sent to the httpserver for c.jar");
return false;
}
return true;
}
static boolean javaUtilServiceLoaderTest(URL baseURL,
String serviceClass,
boolean expectToFind,
boolean expectbDotJar,
boolean expectcDotJar) throws IOException {
debug("----------------------------------");
debug("Running test with java.util.ServiceLoader looking for " + serviceClass);
URLClassLoader loader = getLoader(baseURL);
httpServer.reset();
Class<?> messageServiceClass = null;
try {
messageServiceClass = loader.loadClass(serviceClass);
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
throw new RuntimeException("Error in test: " + cnfe);
}
Iterator<?> iterator = (ServiceLoader.load(messageServiceClass, loader)).iterator();
if (expectToFind && !iterator.hasNext()) {
debug(messageServiceClass + " NOT found.");
return false;
}
while (iterator.hasNext()) {
debug("found " + iterator.next() + " " + messageService);
}
debug("HttpServer: " + httpServer);
if (!expectbDotJar && httpServer.bDotJar > 0) {
debug("Unexpeced request sent to the httpserver for b.jar");
return false;
}
if (!expectcDotJar && httpServer.cDotJar > 0) {
debug("Unexpeced request sent to the httpserver for c.jar");
return false;
}
return true;
}
static boolean javaUtilServiceLoaderTest(URL baseURL,
String serviceClass,
boolean expectToFind,
boolean expectbDotJar,
boolean expectcDotJar) throws IOException {
debug("----------------------------------");
debug("Running test with java.util.ServiceLoader looking for " + serviceClass);
URLClassLoader loader = getLoader(baseURL);
httpServer.reset();
Class<?> messageServiceClass = null;
try {
messageServiceClass = loader.loadClass(serviceClass);
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
throw new RuntimeException("Error in test: " + cnfe);
}
Iterator<?> iterator = (ServiceLoader.load(messageServiceClass, loader)).iterator();
if (expectToFind && !iterator.hasNext()) {
debug(messageServiceClass + " NOT found.");
return false;
}
while (iterator.hasNext()) {
debug("found " + iterator.next() + " " + messageService);
}
debug("HttpServer: " + httpServer);
if (!expectbDotJar && httpServer.bDotJar > 0) {
debug("Unexpeced request sent to the httpserver for b.jar");
return false;
}
if (!expectcDotJar && httpServer.cDotJar > 0) {
debug("Unexpeced request sent to the httpserver for c.jar");
return false;
}
return true;
}
static boolean sunMiscServiceTest(URL baseURL,
String serviceClass,
boolean expectToFind,
boolean expectbDotJar,
boolean expectcDotJar) throws IOException {
debug("----------------------------------");
debug("Running test with sun.misc.Service looking for " + serviceClass);
URLClassLoader loader = getLoader(baseURL);
httpServer.reset();
Class<?> messageServiceClass = null;
try {
messageServiceClass = loader.loadClass(serviceClass);
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
throw new RuntimeException("Error in test: " + cnfe);
}
Iterator<?> iterator = sun.misc.Service.providers(messageServiceClass, loader);
if (expectToFind && !iterator.hasNext()) {
debug(messageServiceClass + " NOT found.");
return false;
}
while (iterator.hasNext()) {
debug("found " + iterator.next() + " " + messageService);
}
debug("HttpServer: " + httpServer);
if (!expectbDotJar && httpServer.bDotJar > 0) {
debug("Unexpeced request sent to the httpserver for b.jar");
return false;
}
if (!expectcDotJar && httpServer.cDotJar > 0) {
debug("Unexpeced request sent to the httpserver for c.jar");
return false;
}
return true;
}