问题描述
采用javassist来将一个类中的field改变类型。待改变的类代码如下:public class JassistTest {@Autowiredprivate StpService stpService;public void doit(Long userid){PeakSeasonMainResponse res = stpService.getPeakOverView(userid);System.out.println(stpService.getClass().getName());System.out.println("hello" + res);}}进行改变操作的类如下:public class TestMain {public TestMain(){}public static void main(String[] args) throws Exception{ClassPool pool = ClassPool.getDefault();CtClass cc = pool.get("JassistTest");CtField f = cc.getDeclaredField("stpService");cc.removeField(f);cc.addField(CtField.make("private Proxy stpService;", cc));cc.writeFile("D:\DevProgram\eclipse-jee-kepler-R-win32\workspace\stable\fc-deimos\target\test-classes");JassistTest test = new JassistTest();test.doit(7060L);}}class文件生成后,我用反编译工具查看,Javassist已经变为如下:public class JassistTest{ private Proxy stpService; public void doit(Long userid) { PeakSeasonMainResponse res = this.stpService.getPeakOverView(userid); System.out.println(this.stpService.getClass().getName()); System.out.println("hello" + res); }}但当我执行TestMain.java文件中的test.doit()方法时,还是报异常了。Exception in thread "main" java.lang.NoSuchFieldError: stpServiceat JassistTest.doit(JassistTest.java:13)at TestMain.main(TestMain.java:33)实在搞不懂,请教大家
解决方案
感觉跟classloader有关,试试这样,分开两次执行。第一次生成新的class,第二次把在path里直接使用新的class文件