package classloader;

import java.lang.reflect.Method;

import org.junit.Test;

import com.example.Sample;

public class ClassIdentity {

    public static void main(String[] args) {

//        new ClassIdentity().testClassIdentity();
// System.out.println("执行了吗"); new ClassIdentity().testICalculator();
} public void testICalculator(){ String basicClassName = "com.example.CalculatorBasic";
String advancedClassName = "com.example.CalculatorAdvanced";
String classDataRootPath = "C:\\";
FileSystemClassLoader fscl1 = new FileSystemClassLoader(classDataRootPath); try {
Class<?> class1 = fscl1.loadClass(basicClassName);
//下面这句会导致fscl1尝试加载在C:\下面加载classloader.ICalculator
ICalculator calculator=(ICalculator)class1.newInstance();
System.out.println(calculator.getVersion());
System.out.println( ICalculator.class.getClassLoader());
System.out.println( calculator.getClass().getClassLoader());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
@Test
public void testClassIdentity() {
String classDataRootPath = "C:\\";
FileSystemClassLoader fscl1 = new FileSystemClassLoader(classDataRootPath);
FileSystemClassLoader fscl2 = new FileSystemClassLoader(classDataRootPath);
String className = "com.example.Sample";
try {
Class<?> class1 = fscl1.loadClass(className);
Object obj1 = class1.newInstance(); Class<?> class2 = fscl2.loadClass(className);
Object obj2 = class2.newInstance(); System.out.println("不同加载器->" + class1.equals(class2)); Class<?> c1= this.getClass().getClassLoader().loadClass("classloader.Versioned");
Class<?> c2= this.getClass().getClassLoader().loadClass("classloader.Versioned"); System.out.println("同一个->" + c1.equals(c2)); Method setSampleMethod = class1.getMethod("setSample", java.lang.Object.class);
// setSampleMethod.invoke(obj1, obj1);
// setSampleMethod.invoke(obj1, obj1);
System.out.println( Sample.class.getClassLoader());
System.out.println( ClassIdentity.class.getClassLoader());
System.out.println(obj1.getClass().getClassLoader() );
Sample sample=(Sample)obj1; //无法将obj1转化成Sample,引用的类加载器不同
} catch (Exception e) {
e.printStackTrace();
}
}
}

testICalculator()输出:
这里com.example.CalculatorBasic
这里classloader.ICalculator
这里java.lang.Object
1.0
sun.misc.Launcher$AppClassLoader@105d88a
classloader.FileSystemClassLoader@76fba0

改写类加载器

package classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; public class FileSystemClassLoader extends ClassLoader { private String rootDir; public FileSystemClassLoader(String rootDir) {
this.rootDir = rootDir;
} protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classData = getClassData(name);
if (classData == null) {
throw new ClassNotFoundException();
}
else {
return defineClass(name, classData, 0, classData.length);
}
} private byte[] getClassData(String className) {
String path = classNameToPath(className);
try {
InputStream ins = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesNumRead = 0;
while ((bytesNumRead = ins.read(buffer)) != -1) {
baos.write(buffer, 0, bytesNumRead);
}
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} private String classNameToPath(String className) {
return rootDir + File.separatorChar
+ className.replace('.', File.separatorChar) + ".class";
} @Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException{
System.out.println("这里" + name);
if("java.lang.Object".equals(name)
|| "classloader.ICalculator".equals(name)
){
return super.loadClass(name, resolve);
} return findClass(name);
} }

注释//Sample sample=(Sample)obj1; 后的输出:
这里com.example.Sample
这里java.lang.Object
这里com.example.Sample
这里java.lang.Object
不同加载器->false
同一个->true
sun.misc.Launcher$AppClassLoader@105d88a
sun.misc.Launcher$AppClassLoader@105d88a
classloader.FileSystemClassLoader@1866417

打开注释后的输出:

这里com.example.Sample
这里java.lang.Object
这里com.example.Sample
这里java.lang.Object
不同加载器->false
同一个->true
sun.misc.Launcher$AppClassLoader@105d88a
sun.misc.Launcher$AppClassLoader@105d88a
classloader.FileSystemClassLoader@1526e3
java.lang.ClassCastException: com.example.Sample cannot be cast to com.example.Sample

java类加载器的一些测试的更多相关文章

  1. 深入探讨 Java 类加载器

    转自:http://www.ibm.com/developerworks/cn/java/j-lo-classloader/ 类加载器(class loader)是 Java™中的一个很重要的概念.类 ...

  2. 深入探讨 Java 类加载器[转]

    原文地址:http://www.ibm.com/developerworks/cn/java/j-lo-classloader/index.html 类加载器(class loader)是 Java™ ...

  3. 转载:深入探讨 Java 类加载器

    转载地址 : http://www.ibm.com/developerworks/cn/java/j-lo-classloader/ 深入探讨 Java 类加载器 类加载器(class loader) ...

  4. 全面解析Java类加载器

    深入理解和探究Java类加载机制---- 1.java.lang.ClassLoader类介绍 java.lang.ClassLoader类的基本职责就是根据一个指定的类的名称,找到或者生成其对应的字 ...

  5. Java类加载器学习笔记

    今后一段时间会全面读一下<深入理解Java虚拟机> 在这里先记一下在网上看到的几篇介绍 类加载器 的文章,等读到虚拟机类加载机制再详细介绍. 超详细Java中的ClassLoader详解 ...

  6. Java基础-类加载机制与自定义类Java类加载器(ClassLoader)

    Java基础-类加载机制与自定义类Java类加载器(ClassLoader) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 关于类加载器的概念和分类我就不再废话了,因为我在之前的笔 ...

  7. 深入理解Java类加载器(ClassLoader) (转)

    转自: http://blog.csdn.net/javazejian/article/details/73413292 关联文章: 深入理解Java类型信息(Class对象)与反射机制 深入理解Ja ...

  8. 深入探讨 Java 类加载器(转载)

    类加载器(class loader)是 Java™中的一个很重要的概念.类加载器负责加载 Java 类的字节代码到 Java 虚拟机中.本文首先详细介绍了 Java 类加载器的基本概念,包括代理模式. ...

  9. java类加载器-----用户自定义类加载器实现

    java类加载器主要分为如下几种: jvm提供的类加载器 根类加载器:底层实现,主要加载java核心类库(如:java.lang.*) 扩展类加载器:使用java代码实现,主要加载如:jre/lib/ ...

随机推荐

  1. 打造基于jQuery的日期选择控件

    终于把jQuery拼写正确了哈,哈哈javascript也是区分大小写的,所以确实不能写错,今天我来和大家分享的是日期选择控件的实现,功能也许不够强大,但是能够满足需求. 我之前也写过(正确的说是改过 ...

  2. IAR 9+ 编译 TI CC2541 出现 Segment ISTACK (size: 0xc0 align: 0) is too long for segment definition.

    IAR 9+ 编译 TI CC2541 出现 Segment ISTACK (size: 0xc0 align: 0) is too long for segment definition. Segm ...

  3. 【转】MFC消息处理(一)

    原文网址:http://blog.csdn.net/hyhnoproblem/article/details/6182120 1.MFC窗口如何与AfxWndProc建立联系. 当一个新的CWnd派生 ...

  4. LINQ to SQL 系列 如何使用LINQ to SQL插入、修改、删除数据 (转)

    http://www.cnblogs.com/yukaizhao/archive/2010/05/13/linq_to_sql_1.html LINQ和 LINQ to SQL 都已经不是一个新事物了 ...

  5. 3.Appium运行时出现:Original error: Android devices must be of API level 17 or higher. Please change your device to Selendroid or upgrade Android on your device

    参考博客:https://blog.csdn.net/niubitianping/article/details/52624417 1.错误信息:Original error: Android dev ...

  6. laravel中生成支付宝 二维码 扫码支付

    文档教程模拟: http://www.023xs.cn/Article/37/laravel5%E9%9B%86%E6%88%90%E6%94%AF%E4%BB%98%E5%AE%9Dalipay%E ...

  7. sql server常用日期格式化

    /*8 24 108 - hh:mm:ss */ Select CONVERT(varchar(), GETDATE(), )-- :: Select CONVERT(varchar(), GETDA ...

  8. 使用SafeViewFlipper避免ViewFlipper交替时Crash

    使用SafeViewFlipper避免ViewFlipper交替时Crash 柳志超博客 » Program » Andriod » 使用SafeViewFlipper避免ViewFlipper交替时 ...

  9. lodop打印控件需要开启的几个计算机服务

    首先要开启: 其次:

  10. 1021 docker初识

    docker与虚拟机相比,没有虚拟化内核,转而使用宿主机的内核.因此docker更轻更快 docker缺点:后端兼容性测试需求.把软件安装在不同的操作系统上进行测试,观察软件运行是否良好. 不能用do ...