|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {
MyClassloader myClassloader = new MyClassloader("D:\\javacode3\\thread-exercise\\target\\classes\\com\\karson\\test\\");
Class<?> garbage = myClassloader.loadClass("Garbage");
Method say = garbage.getDeclaredMethod("say");
Object instance = garbage.getDeclaredConstructor().newInstance();
if (instance instanceof Garbage){
System.out.println("yes");
}
say.invoke(instance,null);
System.out.println(instance);
System.out.println(garbage.getClassLoader());
}
//报错信息
hello
Exception in thread "main" java.lang.ClassCastException: com.karson.test.Garbage cannot be cast to com.karson.test.Garbage
at com.karson.test.TT.main(TT.java:32)
//如下是自己定义的类加载加载指定目录下的.class文件
public class MyClassloader extends ClassLoader {
private String byteCodePath;
public MyClassloader(String byteCodePath) {
this.byteCodePath = byteCodePath;
}
public MyClassloader(ClassLoader parent, String byteCodePath) {
super(parent);
this.byteCodePath = byteCodePath;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String path = byteCodePath + name + ".class";
BufferedInputStream bis = null;
ByteArrayOutputStream bao = null;
try {
bis = new BufferedInputStream(new FileInputStream(path));
bao = new ByteArrayOutputStream();
int len;
byte[] data = new byte[1024];
while ((len = bis.read(data)) != -1){
bao.write(data,0,len);
}
byte[] byteCodes = bao.toByteArray();
return defineClass(null,byteCodes,0,byteCodes.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bao != null){
try {
bao.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
} |
|