2 yinbucheng yinbucheng 于 2016.03.02 21:19 提问

关于自定义类加载器的问题 2C

我写了一个类自定义类加载器,它在读取类时好像只能转成这个类的父类而不能转成这个类
这是为啥,大神有谁会

3个回答

yinbucheng
yinbucheng   2016.03.02 21:21

我复写是findClass方法

luochoudan
luochoudan   Ds   Rxr 2016.03.02 22:08

最好把代码贴一下。果如你所说,应该不会。如果重写findClass()方法,加载器就会根据类名来查找类。你说的明显是覆盖了默认类加载器的父类委托,应该是重写了loadClass()方法才是。

yinbucheng
yinbucheng   2016.03.03 14:47

package cn.itcast.demo;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class MyClassLoader extends ClassLoader{
private String pathDir;
public MyClassLoader(){

}

public MyClassLoader(String pathDir){
this.pathDir = pathDir;
}

@Override
public Class<?> findClass(String name)throws ClassNotFoundException{
String classFileName = pathDir + "\" +name.substring(name.lastIndexOf(".")+1)+".class";
System.out.println(classFileName);
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try{
fis = new FileInputStream(classFileName);
bos = new ByteArrayOutputStream();
cypher(fis,bos);
fis.close();
byte[] bytes = bos.toByteArray();
return defineClass(null,bytes,0,bytes.length);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(fis!=null)
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
fis = null;
}
try {
if(bos!=null)
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bos=null;
}
}
return super.findClass(name);
}

private static void cypher(FileInputStream fis, OutputStream os) throws IOException {
// TODO Auto-generated method stub
int b = -1;
while((b=fis.read())!=-1){
os.write(b^0xff);
}
}

public static void main(String[] args) throws Exception{
// Scanner scanner = new Scanner(System.in);
// String srcPath = scanner.nextLine();
String srcPath = "F:\MyEclipse 10\test\bin\cn\itcast\demo\Person.class";
String descDir = "testlib";
String descFileName = srcPath.substring(srcPath.lastIndexOf("\"));
String descPath = descDir + descFileName;
FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(descPath);
cypher(fis,fos);
fis.close();
fos.close();
}
}

package cn.itcast.demo;

public class Person extends Animal{
private int age=12;
private String name="yucui";
public void show(){
System.out.println("name:"+name+" age:"+age);
}
}

package cn.itcast.demo;

public class Animal {
private String name2 = "human";
public String getName2(){
return name2;
}
}

它只能转变为animal类型用我自定义类加载器时

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!