注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

和申的个人主页

专注于java开发,1985wanggang

 
 
 

日志

 
 

多个类加载器加载时的classcastException ,和反射赋值  

2012-03-14 20:46:07|  分类: Java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
类加载器1:

package heshen.classloader;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;


public class MyClassLoader1 extends ClassLoader{
private String baseDir;


public MyClassLoader1 (ClassLoader parent, String baseDir) {
super(parent);
this.baseDir = baseDir;
}

@Override
protected Class findClass(String name) throws ClassNotFoundException {
// TODO Auto-generated method stub

byte[] bytes = loadClassBytes(name);
Class theClass = defineClass(name, bytes, 0, bytes.length);
if(theClass == null) {
throw new ClassFormatError();
}
return theClass;
}
private byte[] loadClassBytes(String className) throws ClassNotFoundException {
// TODO Auto-generated method stub
try{
String classFile = getClassFile(className);
System.out.println("classFile:"+classFile);
URL url = new URL(classFile);

BufferedInputStream bis = new BufferedInputStream(url.openStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;

while((i = bis.read()) != -1) {
baos.write(i);
}

return baos.toByteArray();

} catch(IOException e) {
throw new ClassNotFoundException(className);
}

// return null;
}
private String getClassFile(String name) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer(baseDir);
name = name.replace('.', File.separatorChar) + ".class";
sb.append(File.separator + name);
return sb.toString();
}
}


类加载器2

package heshen.classloader;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;


public class MyClassLoader2 extends ClassLoader {
private String baseDir;


public MyClassLoader2 (ClassLoader parent, String baseDir) {
super(parent);
this.baseDir = baseDir;
}

@Override
protected Class findClass(String name) throws ClassNotFoundException {
// TODO Auto-generated method stub

byte[] bytes = loadClassBytes(name);
Class theClass = defineClass(name, bytes, 0, bytes.length);
if(theClass == null) {
throw new ClassFormatError();
}
return theClass;
}
private byte[] loadClassBytes(String className) throws ClassNotFoundException {
// TODO Auto-generated method stub
try{
String classFile = getClassFile(className);

URL url = new URL(classFile);

BufferedInputStream bis = new BufferedInputStream(url.openStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;

while((i = bis.read()) != -1) {
baos.write(i);
}

return baos.toByteArray();

} catch(IOException e) {
throw new ClassNotFoundException(className);
}

// return null;
}
private String getClassFile(String name) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer(baseDir);
name = name.replace('.', File.separatorChar) + ".class";
sb.append(File.separator + name);
return sb.toString();
}
}


测试类SomeClass

/**
*
*/
package heshen.classloader;

/**
* @author wanggang
*
*/
public class SomeClass {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}


测试类

/**
*
*/
package heshen.classloader;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
* @author wanggang
*
*/
public class Test {


/**
* @param args
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws NoSuchFieldException
*/
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {

ClassLoader parent = null;
String baseDir = Test.class.getResource("../..").toString();
baseDir = baseDir.substring(0, baseDir.length() -1);
System.out.println(baseDir);

MyClassLoader1 classLoder1 = new MyClassLoader1(parent,baseDir);
MyClassLoader2 classLoder2 = new MyClassLoader2(parent,baseDir);
String name = "heshen.classloader.Some";

Class<?> clazz1 = classLoder1.loadClass(name);
Class<?> clazz2 = classLoder2.loadClass(name);
Object obj1 = clazz1.newInstance();
Object obj2 = clazz2.newInstance();

System.out.println("obj1 ClassLoader:"+obj1.getClass().getClassLoader().getClass().getName());
System.out.println("default ClassLoader:"+SomeClass.class.getClassLoader().getClass().getName());


Object someClass = prePareSomeClass(classLoder1);
setValue(obj1,"setSomeClass",someClass,someClass.getClass());
System.out.println("=========== 拷贝参数前 =============");
printObj(obj1);
printObj(obj2);
long start = System.nanoTime();
//使用反射拷贝参数
copyProperties( obj1, obj2);
System.out.println("copytime:"+(System.nanoTime() -start) );
System.out.println("=========== 拷贝参数后 =============");
printObj(obj1);
printObj(obj2);

}

private static Object prePareSomeClass(ClassLoader classLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException{
Class<?> someClassclazz1 = classLoader.loadClass("heshen.classloader.SomeClass");
Object obj = someClassclazz1.newInstance();
setValue(obj,"setName","what's",String.class);
return obj;
}

private static void setValue(Object obj,String methodName,Object value,Class<?> argsClass) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException{
Class<?> clazz1 = obj.getClass();
Method setMethod1 = clazz1.getMethod(methodName, argsClass);
setMethod1.invoke(obj, value);
}

private static void printObj(Object obj) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
if(obj != null){
Class<?> clazz = obj.getClass();
ClassLoader classLoader = clazz.getClassLoader();
System.out.print("className:" + clazz.getName() +", "+ "classLoader:"+ (classLoader == null ? null : classLoader.getClass().getName()));
Method[] ms = clazz.getDeclaredMethods();
for(Method m :ms){
if(m.getName().startsWith("get")){
Object o = m.invoke(obj);

Class<?> clazzO = null;
if(o != null){
clazzO = o.getClass();
}
if(o instanceof String || o instanceof Number){
System.out.print(" ,method:{key:"+m.getName()+",value:"+o +"}");

}else{
System.out.println();
System.out.print("-----|key:" + (clazzO == null ? null:clazzO.getName()) + ",value:{");
printObj(o);
System.out.print("}");
System.out.println();
}

}

}
}
}

private static void copyProperties(Object obj1, Object obj2) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException, ClassNotFoundException, InstantiationException{
if(obj1 != null && obj2 != null){

Class<?> clazz1 = obj1.getClass();
Class<?> clazz2 = obj2.getClass();
Field[] fields = clazz1.getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
String fieldName = field.getName();
Object fieldValue = field.get(obj1);
Field field2 = clazz2.getDeclaredField(fieldName);
field2.setAccessible(true);
Class<?> fieldClazz = fieldValue.getClass();
if(fieldValue instanceof String || fieldValue instanceof Number){
field2.set(obj2, fieldValue);
}else{
Class<?> clazzfieldValueTo = clazz2.getClassLoader().loadClass(fieldClazz.getName());
Object fieldValueTo = clazzfieldValueTo.newInstance();
copyProperties(fieldValue, fieldValueTo );
field2.set(obj2, fieldValueTo);
}


}
}
}

}



运行结果:
file:/home/wanggang/workspace/OtherTest/bin
classFile:file:/home/wanggang/workspace/OtherTest/bin/heshen/classloader/Some.class
obj1 ClassLoader:heshen.classloader.MyClassLoader1
default ClassLoader:sun.misc.Launcher$AppClassLoader
classFile:file:/home/wanggang/workspace/OtherTest/bin/heshen/classloader/SomeClass.class
=========== 拷贝参数前 =============
className:heshen.classloader.Some, classLoader:heshen.classloader.MyClassLoader1
-----|key:heshen.classloader.SomeClass,value:{className:heshen.classloader.SomeClass, classLoader:heshen.classloader.MyClassLoader1 ,method:{key:getName,value:what's}}
-------------------------------------------------------
className:heshen.classloader.Some, classLoader:heshen.classloader.MyClassLoader2
-----|key:null,value:{}
copytime:476842
=========== 拷贝参数后 =============
className:heshen.classloader.Some, classLoader:heshen.classloader.MyClassLoader1
-----|key:heshen.classloader.SomeClass,value:{className:heshen.classloader.SomeClass, classLoader:heshen.classloader.MyClassLoader1 ,method:{key:getName,value:what's}}
-------------------------------------------------------
className:heshen.classloader.Some, classLoader:heshen.classloader.MyClassLoader2
-----|key:heshen.classloader.SomeClass,value:{className:heshen.classloader.SomeClass, classLoader:heshen.classloader.MyClassLoader2 ,method:{key:getName,value:what's}}
  评论这张
 
阅读(738)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2016