Instrumentation的其他用法

运行时替换类:

byte[] buf = getWrappedClass(className,methods);         //这里一般是用asm修改字节码,得到修改后的类字节码的字节数组
                                                                                
                                                                                 // 将包装后的类写出到文件,以供研究之用。
                                                         //OutputStream out = new FileOutputStream("d:/my/TestClass.class");
                                                         //out.write(buf);
                                                         //out.close();
                                                        
                                                        
                                                         //运行时替换类        
                                                                                Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass(className);        
                                                                                
                                                                                ClassDefinition[] definitions = new ClassDefinition[] { new ClassDefinition(clazz, buf) };        
                                                                                inst.redefineClasses(definitions);

得到原始类字节码(不适用于Spring或者Hibernate修改后的类):
private static byte[] getOriginClass(String className){    
                 try{    
                        String path = className.replace('.', '/') + ".class";    
                        ClassReader reader = new ClassReader(ClassLoader.getSystemResourceAsStream(path));    
                         return reader.b;    
                } catch(Exception e){    
                        e.printStackTrace(System.out);    
                }    
                 return null;    
        }

将原始类字节数组缓存起来,然后,就可以进行还原,还原的代码也是一样的:
Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass(className);    
                                        ClassDefinition[] definitions = new ClassDefinition[] { new ClassDefinition(clazz, buf) };    
                                        inst.redefineClasses(definitions);

其中,buf就是缓存下来的类的原始的字节数组。

你可能感兴趣的:(Instrumentation)