java.lang.ClassLoader类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(8.3k)|赞(0)|评价(0)|浏览(185)

本文整理了Java中java.lang.ClassLoader类的一些代码示例,展示了ClassLoader类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ClassLoader类的具体详情如下:
包路径:java.lang.ClassLoader
类名称:ClassLoader

ClassLoader介绍

[英]Loads classes and resources from a repository. One or more class loaders are installed at runtime. These are consulted whenever the runtime system needs a specific class that is not yet available in-memory. Typically, class loaders are grouped into a tree where child class loaders delegate all requests to parent class loaders. Only if the parent class loader cannot satisfy the request, the child class loader itself tries to handle it.

ClassLoader is an abstract class that implements the common infrastructure required by all class loaders. Android provides several concrete implementations of the class, with dalvik.system.PathClassLoader being the one typically used. Other applications may implement subclasses of ClassLoader to provide special ways for loading classes.
[中]从存储库加载类和资源。在运行时安装一个或多个类加载器。每当运行时系统需要内存中尚不可用的特定类时,都会参考这些类。通常,类加载器被分组到树中,子类加载器将所有请求委托给父类加载器。只有当父类加载器不能满足请求时,子类加载器才会尝试处理它。
ClassLoader是一个抽象类,它实现所有类装入器所需的公共基础结构。Android使用dalvik提供了该类的几个具体实现。系统PathClassLoader是通常使用的一个。其他应用程序可能实现ClassLoader的子类,以提供加载类的特殊方式。

代码示例

代码示例来源:origin: jenkinsci/jenkins

/**
 * Finds a system resource (which should be loaded from the parent
 * classloader).
 *
 * @param name The name of the system resource to load.
 *             Must not be <code>null</code>.
 *
 * @return a stream to the named resource, or <code>null</code> if
 *         the resource cannot be found.
 */
private InputStream loadBaseResource(String name) {
  return parent == null ? super.getResourceAsStream(name) : parent.getResourceAsStream(name);
}

代码示例来源:origin: apache/incubator-dubbo

@Override
protected synchronized Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
  return super.loadClass(name, resolve);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public URL getResource(String name) {
  return this.enclosingClassLoader.getResource(name);
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Resolves a URL for the underlying class path resource.
 * @return the resolved URL, or {@code null} if not resolvable
 */
@Nullable
protected URL resolveURL() {
  if (this.clazz != null) {
    return this.clazz.getResource(this.path);
  }
  else if (this.classLoader != null) {
    return this.classLoader.getResource(this.path);
  }
  else {
    return ClassLoader.getSystemResource(this.path);
  }
}

代码示例来源:origin: redisson/redisson

/**
 * Returns an unsafe class injector for the platform class loader. For VMs of version 8 or older,
 * the extension class loader is represented instead.
 *
 * @return A class injector for the platform class loader.
 */
public static ClassInjector ofPlatformLoader() {
  return new UsingUnsafe(ClassLoader.getSystemClassLoader().getParent());
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public Enumeration<URL> getResources(String name) throws IOException {
  return this.enclosingClassLoader.getResources(name);
}

代码示例来源:origin: skylot/jadx

private static void load(LangLocale locale) {
  ResourceBundle bundle;
  ClassLoader classLoader = ClassLoader.getSystemClassLoader();
  String resName = String.format("i18n/Messages_%s.properties", locale.get());
  URL bundleUrl = classLoader.getResource(resName);
  if (bundleUrl == null) {
    throw new JadxRuntimeException("Locale resource not found: " + resName);
  }
  try (Reader reader = new InputStreamReader(bundleUrl.openStream(), StandardCharsets.UTF_8)) {
    bundle = new PropertyResourceBundle(reader);
  } catch (IOException e) {
    throw new JadxRuntimeException("Failed to load " + resName, e);
  }
  i18nMessagesMap.put(locale, bundle);
}

代码示例来源:origin: netty/netty

static ClassLoader getSystemClassLoader() {
  if (System.getSecurityManager() == null) {
    return ClassLoader.getSystemClassLoader();
  } else {
    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
      @Override
      public ClassLoader run() {
        return ClassLoader.getSystemClassLoader();
      }
    });
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Find all class location resources with the given path via the ClassLoader.
 * Called by {@link #findAllClassPathResources(String)}.
 * @param path the absolute path within the classpath (never a leading slash)
 * @return a mutable Set of matching Resource instances
 * @since 4.1.1
 */
protected Set<Resource> doFindAllClassPathResources(String path) throws IOException {
  Set<Resource> result = new LinkedHashSet<>(16);
  ClassLoader cl = getClassLoader();
  Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path));
  while (resourceUrls.hasMoreElements()) {
    URL url = resourceUrls.nextElement();
    result.add(convertClassLoaderURL(url));
  }
  if ("".equals(path)) {
    // The above result is likely to be incomplete, i.e. only containing file system references.
    // We need to have pointers to each of the jar files on the classpath as well...
    addAllClassLoaderJarRoots(cl, result);
  }
  return result;
}

代码示例来源:origin: redisson/redisson

/**
 * {@inheritDoc}
 */
public boolean matches(T target) {
  ClassLoader current = classLoader;
  while (current != null) {
    if (current == target) {
      return true;
    }
    current = current.getParent();
  }
  return target == null;
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Returns the URL of the index page jelly script.
 */
public URL getIndexPage() {
  // In the current impl dependencies are checked first, so the plugin itself
  // will add the last entry in the getResources result.
  URL idx = null;
  try {
    Enumeration<URL> en = classLoader.getResources("index.jelly");
    while (en.hasMoreElements())
      idx = en.nextElement();
  } catch (IOException ignore) { }
  // In case plugin has dependencies but is missing its own index.jelly,
  // check that result has this plugin's artifactId in it:
  return idx != null && idx.toString().contains(shortName) ? idx : null;
}

代码示例来源:origin: google/guava

private static ImmutableList<URL> getClassLoaderUrls(ClassLoader classloader) {
 if (classloader instanceof URLClassLoader) {
  return ImmutableList.copyOf(((URLClassLoader) classloader).getURLs());
 }
 if (classloader.equals(ClassLoader.getSystemClassLoader())) {
  return parseJavaClassPath();
 }
 return ImmutableList.of();
}

代码示例来源:origin: redisson/redisson

/**
 * Returns a type pool that attempts type descriptions by loadings types from the platform class loader.
 * If the current VM is Java 8 or older, the extension class loader is represented instead.
 *
 * @return An class loading type pool for the system class loader.
 */
public static TypePool ofPlatformLoader() {
  return of(ClassLoader.getSystemClassLoader().getParent());
}

代码示例来源:origin: apache/incubator-dubbo

private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type) {
  String fileName = dir + type;
  try {
    Enumeration<java.net.URL> urls;
    ClassLoader classLoader = findClassLoader();
    if (classLoader != null) {
      urls = classLoader.getResources(fileName);
    } else {
      urls = ClassLoader.getSystemResources(fileName);
    }
    if (urls != null) {
      while (urls.hasMoreElements()) {
        java.net.URL resourceURL = urls.nextElement();
        loadResource(extensionClasses, classLoader, resourceURL);
      }
    }
  } catch (Throwable t) {
    logger.error("Exception occurred when loading extension class (interface: " +
        type + ", description file: " + fileName + ").", t);
  }
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Used for isolated resource seaching.
 * @return the root classloader of AntClassLoader.
 */
private ClassLoader getRootLoader() {
  ClassLoader ret = getClass().getClassLoader();
  while (ret != null && ret.getParent() != null) {
    ret = ret.getParent();
  }
  return ret;
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public InputStream getResourceAsStream(String name) {
  return this.enclosingClassLoader.getResourceAsStream(name);
}

代码示例来源:origin: apache/incubator-dubbo

@Override
protected synchronized Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
  return super.loadClass(name, resolve);
}

代码示例来源:origin: apache/incubator-dubbo

private static boolean hasResource(String path) {
  try {
    return Version.class.getClassLoader().getResource(path) != null;
  } catch (Throwable t) {
    return false;
  }
}

代码示例来源:origin: redisson/redisson

/**
 * {@inheritDoc}
 */
public Enumeration<URL> getResources(String name) throws IOException {
  List<Enumeration<URL>> enumerations = new ArrayList<Enumeration<URL>>(parents.size() + 1);
  for (ClassLoader parent : parents) {
    enumerations.add(parent.getResources(name));
  }
  enumerations.add(super.getResources(name));
  return new CompoundEnumeration(enumerations);
}

代码示例来源:origin: alibaba/druid

public static Properties loadFilterConfig() throws IOException {
  Properties filterProperties = new Properties();
  loadFilterConfig(filterProperties, ClassLoader.getSystemClassLoader());
  loadFilterConfig(filterProperties, FilterManager.class.getClassLoader());
  loadFilterConfig(filterProperties, Thread.currentThread().getContextClassLoader());
  loadFilterConfig(filterProperties, FilterManager.class.getClassLoader());
  return filterProperties;
}

相关文章