自定义类加载器( 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 配置文件之类型、加载顺序与最佳实践记录

《SpringBoot配置文件之类型、加载顺序与最佳实践记录》SpringBoot的配置文件是灵活且强大的工具,通过合理的配置管理,可以让应用开发和部署更加高效,无论是简单的属性配置,还是复杂... 目录Spring Boot 配置文件详解一、Spring Boot 配置文件类型1.1 applicatio

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

SpringBoot项目启动报错"找不到或无法加载主类"的解决方法

《SpringBoot项目启动报错找不到或无法加载主类的解决方法》在使用IntelliJIDEA开发基于SpringBoot框架的Java程序时,可能会出现找不到或无法加载主类com.example.... 目录一、问题描述二、排查过程三、解决方案一、问题描述在使用 IntelliJ IDEA 开发基于

基于Spring实现自定义错误信息返回详解

《基于Spring实现自定义错误信息返回详解》这篇文章主要为大家详细介绍了如何基于Spring实现自定义错误信息返回效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录背景目标实现产出背景Spring 提供了 @RestConChina编程trollerAdvice 用来实现 HTT

SpringSecurity 认证、注销、权限控制功能(注销、记住密码、自定义登入页)

《SpringSecurity认证、注销、权限控制功能(注销、记住密码、自定义登入页)》SpringSecurity是一个强大的Java框架,用于保护应用程序的安全性,它提供了一套全面的安全解决方案... 目录简介认识Spring Security“认证”(Authentication)“授权” (Auth

Android WebView无法加载H5页面的常见问题和解决方法

《AndroidWebView无法加载H5页面的常见问题和解决方法》AndroidWebView是一种视图组件,使得Android应用能够显示网页内容,它基于Chromium,具备现代浏览器的许多功... 目录1. WebView 简介2. 常见问题3. 网络权限设置4. 启用 JavaScript5. D

SpringBoot项目启动错误:找不到或无法加载主类的几种解决方法

《SpringBoot项目启动错误:找不到或无法加载主类的几种解决方法》本文主要介绍了SpringBoot项目启动错误:找不到或无法加载主类的几种解决方法,具有一定的参考价值,感兴趣的可以了解一下... 目录方法1:更改IDE配置方法2:在Eclipse中清理项目方法3:使用Maven命令行在开发Sprin

SpringBoot自定义注解如何解决公共字段填充问题

《SpringBoot自定义注解如何解决公共字段填充问题》本文介绍了在系统开发中,如何使用AOP切面编程实现公共字段自动填充的功能,从而简化代码,通过自定义注解和切面类,可以统一处理创建时间和修改时间... 目录1.1 问题分析1.2 实现思路1.3 代码开发1.3.1 步骤一1.3.2 步骤二1.3.3