|
| 1 | +importjava.io.Closeable; |
| 2 | +importjava.io.IOException; |
| 3 | +importjava.io.InputStream; |
| 4 | +importjava.lang.reflect.Method; |
| 5 | + |
| 6 | +/* |
| 7 | + 第一周作业: |
| 8 | + 2.(必做)自定义一个 Classloader,加载一个 Hello.xlass 文件,执行 hello 方法,此文件内容是一个 Hello.class 文件所有字节(x=255-x)处理后的文件。文件群里提供。 |
| 9 | + */ |
| 10 | +publicclassXlassLoaderextendsClassLoader{ |
| 11 | + |
| 12 | +publicstaticvoidmain(String[] args) throwsException{ |
| 13 | +// 相关参数 |
| 14 | +finalStringclassName = "Hello"; |
| 15 | +finalStringmethodName = "hello"; |
| 16 | +// 创建类加载器 |
| 17 | +ClassLoaderclassLoader = newXlassLoader(); |
| 18 | +// 加载相应的类 |
| 19 | +Class<?> clazz = classLoader.loadClass(className); |
| 20 | +// 看看里面有些什么方法 |
| 21 | +for (Methodm : clazz.getDeclaredMethods()){ |
| 22 | +System.out.println(clazz.getSimpleName() + "." + m.getName()); |
| 23 | + } |
| 24 | +// 创建对象 |
| 25 | +Objectinstance = clazz.getDeclaredConstructor().newInstance(); |
| 26 | +// 调用实例方法 |
| 27 | +Methodmethod = clazz.getMethod(methodName); |
| 28 | +method.invoke(instance); |
| 29 | + } |
| 30 | + |
| 31 | +@Override |
| 32 | +protectedClass<?> findClass(Stringname) throwsClassNotFoundException{ |
| 33 | +// 如果支持包名, 则需要进行路径转换 |
| 34 | +StringresourcePath = name.replace(".", "/"); |
| 35 | +// 文件后缀 |
| 36 | +finalStringsuffix = ".xlass"; |
| 37 | +// 获取输入流 |
| 38 | +InputStreaminputStream = this.getClass().getClassLoader().getResourceAsStream(resourcePath + suffix); |
| 39 | +try{ |
| 40 | +// 读取数据 |
| 41 | +intlength = inputStream.available(); |
| 42 | +byte[] byteArray = newbyte[length]; |
| 43 | +inputStream.read(byteArray); |
| 44 | +// 转换 |
| 45 | +byte[] classBytes = decode(byteArray); |
| 46 | +// 通知底层定义这个类 |
| 47 | +returndefineClass(name, classBytes, 0, classBytes.length); |
| 48 | + } catch (IOExceptione){ |
| 49 | +thrownewClassNotFoundException(name, e); |
| 50 | + } finally{ |
| 51 | +close(inputStream); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | +// 解码 |
| 56 | +privatestaticbyte[] decode(byte[] byteArray){ |
| 57 | +byte[] targetArray = newbyte[byteArray.length]; |
| 58 | +for (inti = 0; i < byteArray.length; i++){ |
| 59 | +targetArray[i] = (byte) (255 - byteArray[i]); |
| 60 | + } |
| 61 | +returntargetArray; |
| 62 | + } |
| 63 | + |
| 64 | +// 关闭 |
| 65 | +privatestaticvoidclose(Closeableres){ |
| 66 | +if (null != res){ |
| 67 | +try{ |
| 68 | +res.close(); |
| 69 | + } catch (IOExceptione){ |
| 70 | +e.printStackTrace(); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments