自定义类加载器( by quqi99 )

2024-03-12 00:48
文章标签 加载 自定义 quqi99

本文主要是介绍自定义类加载器( by quqi99 ),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

自定义类加载器( by quqi99 )

作者:张华 发表于:2010-03-12

版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本版权声明

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;


/**
* 自定义类加载器
* @version 0.10 2010-3-12
* @author Zhang Hua
*/
public class LicClassLoader extends ClassLoader {
public static boolean TRACE = true;
private static boolean isDecrypt = true; //是否加解密
private String cp;

public static void main(String[] args){
LicClassLoader mcl = new LicClassLoader("E:\\workspace\\3.4\\License\\bin", LicClassLoader.class.getClassLoader());
Thread.currentThread().setContextClassLoader(mcl);
try {
Class c = mcl.loadClass("my.secret.code.License");
Object LicenseObj = c.newInstance();
//这样调用会出错,因为License是由系统类加载器加载的,而obj是由 LicClassLoader加载的,系统类加载器看不到LicClassLoader加载的LicenseObj,只能通过反射调用
// License te = (License)LicenseObj;
Method checkMethod = c.getMethod("validate", new Class[]{String.class});
Object result = checkMethod.invoke(LicenseObj, new Object[]{"a"});
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}

public LicClassLoader(String cp, ClassLoader parent) {
super(parent);
this.cp = cp;
}

@SuppressWarnings("unchecked")
public Class loadClass(String className) throws ClassNotFoundException {
return loadClass(className, false);
}

@SuppressWarnings("unchecked")
protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {

try {
if (TRACE)
System.out.println ("loadClass (" + name + ", " + resolve + ")");
if(name.endsWith("Object")){
System.out.println("");
}
//调用系统方法检查此类是否已经被本classloader实例加载过
Class foundClass = findLoadedClass(name);

//如果不是属性本classloader加载的范畴,请求父加载器加载
if(foundClass == null){
Class parentsVersion = null;
try{
parentsVersion = getParent().loadClass(name);
if(parentsVersion.getClassLoader() != getParent())
foundClass = parentsVersion;
}catch (Exception ignore){}
}

//从自定义的classloader加载
if(foundClass == null){
try{
// foundClass= findClass(name); //从class文件找类
foundClass= findClassFromJar(name,"lic.jar"); //从JAR包中找类
}catch(Exception ignore){}
}

//还不行,调用系统类加载器再试一次
// if(foundClass == null){
// foundClass = findSystemClass(name);
// }

//根据情况决定是否加载关系类
if (resolve && foundClass!=null) {
resolveClass(foundClass);
}
return foundClass;
} catch (Exception e) {
throw new ClassNotFoundException(e.toString());
}
}

//从class中找类
public Class findClass(String className) throws ClassNotFoundException {
if (TRACE)
System.out.println("findClass (" + className + ")");
final String filePath = className.replace('.', '/') + ".class";
final URL classURL = getResource(filePath);
if (classURL == null) {
throw new ClassNotFoundException(className);
} else {
InputStream in = null;
try {
in = classURL.openStream();
final byte[] classBytes = readFully(in);
if(isDecrypt){
crypt(classBytes); //加密
crypt(classBytes); //解密
if (TRACE)
System.out.println("decrypted [" + className + "]");
}
return defineClass(className, classBytes, 0, classBytes.length);
} catch (IOException ioe) {
throw new ClassNotFoundException(className);
} finally {
if (in != null)
try {
in.close();
} catch (Exception ignore) {
}
}
}
}



//从jar中找类
protected Class findClassFromJar(String className, String jarName) throws ClassNotFoundException {
String jarPath = cp + File.separator + jarName;
if(!jarPath.toLowerCase().endsWith(".jar") && !jarPath.toLowerCase().endsWith(".zip"))
jarPath = jarPath + ".jar";
JarInputStream in = null;
if (!(jarPath == null || jarPath == "")) {
try {
in = new JarInputStream(new FileInputStream(jarPath));
JarEntry entry;
while ((entry = in.getNextJarEntry()) != null) {
if (entry.toString().equals(className.replace('.', '/') + ".class")) {
if (entry.getSize() == -1) {
System.err.println("error : can't read the file!");
return null;
}
byte[] classData = new byte[(int) entry.getSize()];
System.out.println("It have found the file : " + className + ". Begin to read the data and load the class。");
in.read(classData);
return defineClass(className, classData, 0, classData.length);
}
}
System.out.println("Haven't found the file " + className + " in " + jarName + ".jar.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
System.out.println("Haven't found the jarFile: " + jarName + ".jar.");
return null;
}
return null;
}


/**
* De/encrypts binary data in a given byte array. Calling the method again
* reverses the encryption.
*/
private static void crypt(final byte[] data) {
for (int i = 8; i < data.length; ++i)
data[i] ^= 0x5A;
}

private static byte[] readFully(final InputStream in) throws IOException {
final ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
final byte[] buf2 = new byte[8 * 1024];
for (int read; (read = in.read(buf2)) > 0;) {
buf1.write(buf2, 0, read);
}
return buf1.toByteArray();
}

}

这篇关于自定义类加载器( by quqi99 )的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/799636

相关文章

spring-boot-starter-thymeleaf加载外部html文件方式

《spring-boot-starter-thymeleaf加载外部html文件方式》本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在SpringBoo... 目录1.Thymeleaf介绍2.springboot使用thymeleaf2.1.引入spring

关于Spring @Bean 相同加载顺序不同结果不同的问题记录

《关于Spring@Bean相同加载顺序不同结果不同的问题记录》本文主要探讨了在Spring5.1.3.RELEASE版本下,当有两个全注解类定义相同类型的Bean时,由于加载顺序不同,最终生成的... 目录问题说明测试输出1测试输出2@Bean注解的BeanDefiChina编程nition加入时机总结问题说明

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...

SpringBoot项目启动后自动加载系统配置的多种实现方式

《SpringBoot项目启动后自动加载系统配置的多种实现方式》:本文主要介绍SpringBoot项目启动后自动加载系统配置的多种实现方式,并通过代码示例讲解的非常详细,对大家的学习或工作有一定的... 目录1. 使用 CommandLineRunner实现方式:2. 使用 ApplicationRunne

SpringBoot项目删除Bean或者不加载Bean的问题解决

《SpringBoot项目删除Bean或者不加载Bean的问题解决》文章介绍了在SpringBoot项目中如何使用@ComponentScan注解和自定义过滤器实现不加载某些Bean的方法,本文通过实... 使用@ComponentScan注解中的@ComponentScan.Filter标记不加载。@C

springboot 加载本地jar到maven的实现方法

《springboot加载本地jar到maven的实现方法》如何在SpringBoot项目中加载本地jar到Maven本地仓库,使用Maven的install-file目标来实现,本文结合实例代码给... 在Spring Boothttp://www.chinasem.cn项目中,如果你想要加载一个本地的ja

最好用的WPF加载动画功能

《最好用的WPF加载动画功能》当开发应用程序时,提供良好的用户体验(UX)是至关重要的,加载动画作为一种有效的沟通工具,它不仅能告知用户系统正在工作,还能够通过视觉上的吸引力来增强整体用户体验,本文给... 目录前言需求分析高级用法综合案例总结最后前言当开发应用程序时,提供良好的用户体验(UX)是至关重要

SpringBoot 自定义消息转换器使用详解

《SpringBoot自定义消息转换器使用详解》本文详细介绍了SpringBoot消息转换器的知识,并通过案例操作演示了如何进行自定义消息转换器的定制开发和使用,感兴趣的朋友一起看看吧... 目录一、前言二、SpringBoot 内容协商介绍2.1 什么是内容协商2.2 内容协商机制深入理解2.2.1 内容

MyBatis延迟加载的处理方案

《MyBatis延迟加载的处理方案》MyBatis支持延迟加载(LazyLoading),允许在需要数据时才从数据库加载,而不是在查询结果第一次返回时就立即加载所有数据,延迟加载的核心思想是,将关联对... 目录MyBATis如何处理延迟加载?延迟加载的原理1. 开启延迟加载2. 延迟加载的配置2.1 使用

Android WebView的加载超时处理方案

《AndroidWebView的加载超时处理方案》在Android开发中,WebView是一个常用的组件,用于在应用中嵌入网页,然而,当网络状况不佳或页面加载过慢时,用户可能会遇到加载超时的问题,本... 目录引言一、WebView加载超时的原因二、加载超时处理方案1. 使用Handler和Timer进行超