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

相关文章

Linux中的自定义协议+序列反序列化用法

《Linux中的自定义协议+序列反序列化用法》文章探讨网络程序在应用层的实现,涉及TCP协议的数据传输机制、结构化数据的序列化与反序列化方法,以及通过JSON和自定义协议构建网络计算器的思路,强调分层... 目录一,再次理解协议二,序列化和反序列化三,实现网络计算器3.1 日志文件3.2Socket.hpp

C语言自定义类型之联合和枚举解读

《C语言自定义类型之联合和枚举解读》联合体共享内存,大小由最大成员决定,遵循对齐规则;枚举类型列举可能值,提升可读性和类型安全性,两者在C语言中用于优化内存和程序效率... 目录一、联合体1.1 联合体类型的声明1.2 联合体的特点1.2.1 特点11.2.2 特点21.2.3 特点31.3 联合体的大小1

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

从入门到精通详解LangChain加载HTML内容的全攻略

《从入门到精通详解LangChain加载HTML内容的全攻略》这篇文章主要为大家详细介绍了如何用LangChain优雅地处理HTML内容,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录引言:当大语言模型遇见html一、HTML加载器为什么需要专门的HTML加载器核心加载器对比表二

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... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码