- packagecom;
- importjava.io.*;
- importjava.net.*;
- importjava.util.*;
- importjava.lang.reflect.Method;
- publicclassCustomClassLoaderextendsURLClassLoader{
- privateFileInputStreaminput=null;//文件输入流
- privateByteArrayOutputStreamout=null;//字节数组输出流
- privateString[]url=null;//类文件加载路径
- privatebyte[]data=null;//类文件字节码
- privateStringextensionalName="";//类文件扩展名
- publicCustomClassLoader(URL[]urls)throwsException{
- super(urls);
- this.url=newString[urls.length];
- for(inti=0;i<urls.length;i++){
- this.url[i]=urls[i].toURI().toString();
- }
- }
- /*
- *解析URL
- */
- privatevoidsetFilePath(){
- for(inti=0;i<this.url.length;i++){
- if(this.url[i].substring(0,4).toLowerCase().equals("file")==true){
- this.url[i]=this.url[i].substring(5);
- }
- }
- }
- /*
- *获得指定类名(包名+类名)文件的字节码
- *@namenameString
- *@returnbyte[]
- */
- privatebyte[]getFileData(Stringname){
- try{
- this.setFilePath();
- for(Stringurl:this.url){
- StringfileName=url+name.replace('.','/').concat(".")+
- this.getExtensionalName();
- input=newFileInputStream(newFile(fileName));
- if(input!=null){
- break;
- }
- }
- out=newByteArrayOutputStream();
- data=newbyte[1024];
- intlen=-1;
- while((len=input.read(data))!=-1){
- out.write(data,0,len);
- }
- data=out.toByteArray();
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- if(input!=null)
- input.close();
- if(out!=null)
- out.close();
- returndata;
- }catch(Exceptione){
- e.printStackTrace();
- returnnull;
- }
- }
- }
- /*
- *根据指定类名查找类文件
- *@paramnameString
- *@returnClass
- */
- protectedClassfindClassByName(Stringname){
- try{
- byte[]data=this.getFileData(name);
- if(data==null){
- returnnull;
- }
- returnthis.defineClass(name,data,0,data.length);
- }catch(Exceptione){
- e.printStackTrace();
- returnnull;
- }
- }
- /*
- *重写loadClass()方法
- *@paramnameString
- *@returnClass
- */
- publicClassloadClass(Stringname){
- Classc=null;
- try{
- c=super.loadClass(name);
- }catch(ClassNotFoundExceptione){
- e.printStackTrace();
- }finally{
- if(c==null)//父类默认方法没有加载到指定类时,使用自定义方法查找
- c=this.findClassByName(name);
- returnc;
- }
- }
- publicStringgetExtensionalName(){
- returnextensionalName;
- }
- publicvoidsetExtensionalName(StringextensionalName){
- this.extensionalName=extensionalName;
- }
- publicstaticvoidmain(String[]args)throwsException{
- URL[]url=newURL[]{newURL("file:e:/")};//添加你想要加载类的路径
- //网络或本地均可
- CustomClassLoadercsl=newCustomClassLoader(url);
- csl.setExtensionalName("rs");
- Classc1=csl.loadClass("com.demo");
- Objectobj=c1.newInstance();
- Methodmethod=c1.getMethod("printText",null);
- method.invoke(obj,null);
- }
- }
自定义类加载器
最新推荐文章于 2021-08-03 23:40:06 发布