自定义类加载器( 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

相关文章

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

一文详解Java Stream的sorted自定义排序

《一文详解JavaStream的sorted自定义排序》Javastream中的sorted方法是用于对流中的元素进行排序的方法,它可以接受一个comparator参数,用于指定排序规则,sorte... 目录一、sorted 操作的基础原理二、自定义排序的实现方式1. Comparator 接口的 Lam

Spring如何使用注解@DependsOn控制Bean加载顺序

《Spring如何使用注解@DependsOn控制Bean加载顺序》:本文主要介绍Spring如何使用注解@DependsOn控制Bean加载顺序,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录1.javascript 前言2. 代码实现总结1. 前言默认情况下,Spring加载Bean的顺

如何自定义一个log适配器starter

《如何自定义一个log适配器starter》:本文主要介绍如何自定义一个log适配器starter的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录需求Starter 项目目录结构pom.XML 配置LogInitializer实现MDCInterceptor

springboot加载不到nacos配置中心的配置问题处理

《springboot加载不到nacos配置中心的配置问题处理》:本文主要介绍springboot加载不到nacos配置中心的配置问题处理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录springboot加载不到nacos配置中心的配置两种可能Spring Boot 版本Nacos

Druid连接池实现自定义数据库密码加解密功能

《Druid连接池实现自定义数据库密码加解密功能》在现代应用开发中,数据安全是至关重要的,本文将介绍如何在​​Druid​​连接池中实现自定义的数据库密码加解密功能,有需要的小伙伴可以参考一下... 目录1. 环境准备2. 密码加密算法的选择3. 自定义 ​​DruidDataSource​​ 的密码解密3

spring-gateway filters添加自定义过滤器实现流程分析(可插拔)

《spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔)》:本文主要介绍spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔),本文通过实例图... 目录需求背景需求拆解设计流程及作用域逻辑处理代码逻辑需求背景公司要求,通过公司网络代理访问的请求需要做请