2011-07-11 182 views
2

我的步驟進行創建動態類如下:CtClass.toClass拋出與消息的異常「空」

 try 
     { 

      classLoader = Class.forName("org.yaddayadda.DynamicClass" + genericType.getName().toLowerCase() + uniqueID); 
     } 
     catch (ClassNotFoundException classNotFoundException) 
     { 
     } 

     if (classLoader == null) 
     { 
      dynamicClass = pool.get("org.yaddayadda.DynamicClass"); 
      dynamicClass.defrost(); 
      dynamicClass.replaceClassName("org.yaddayadda.DynamicClass","org.yaddayadda.DynamicClass"+ genericType.getName().toLowerCase() + uniqueID); 

      dynamicClass.defrost(); 


      CtMethod readObject = dynamicClass.getDeclaredMethod("Method1"); 
      CtMethod writeObject = dynamicClass.getDeclaredMethod("Method2"); 

      StringBuffer method1= new StringBuffer(); 
      StringBuffer method2= new StringBuffer(); 

      GenerateDynamicCode.generateCode(genericType, method1, method2); 

      writeObject.insertAt(1, method1.toString()); 
      readObject.insertAt(1, method2.toString()); 

      //This is where the exception is thrown 
      classLoader = dynamicClass.toClass(); 
     } 

我第一次嘗試檢查類ClassPool已經存在如果不是的話,我繼續上創建一個班級。除霜只爲防故障機制完成。該異常時,如果本方法toClass被稱爲dynamicClass.toClass();

唯一的例外是如下

Exception Message: null 
    Stack Trace: 
    sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source) 
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    java.lang.reflect.Method.invoke(Unknown Source) 
    javassist.ClassPool.toClass2(ClassPool.java:1102) 
    javassist.ClassPool.toClass(ClassPool.java:1083) 
    javassist.ClassPool.toClass(ClassPool.java:1032) 
    javassist.ClassPool.toClass(ClassPool.java:990) 
    javassist.CtClass.toClass(CtClass.java:1125) 
    This Class 

什麼是上述異常的原因,並可以做些什麼來避免呢?

回答

1

嗯,我已經找到了一個解決方案,實際上是一個解決方法,即我只需調用一個循環再次解凍編譯後的類並重做我剛剛嘗試的所有事件,當出現異常並且循環最多運行3次時,安全側

 int i = 0; 
     while (classLoader == null) 
     { 
      try 
      { 
       if (classLoader == null) 
       { 
        dynamicClass = pool.get("org.yaddayadda.DynamicClass"); 
        dynamicClass.defrost(); 


        try 
        { 
         dynamicSurrugate = pool.get("org.yaddayadda.DynamicClass" + genericType.getName().toLowerCase() + uniqueID); 

         dynamicSurrugate.defrost(); 
        } 
        catch (NotFoundException notFoundException) 
        { 
        } 


        //Everything the same 
       } 
      } 
      catch (Exception exception) 
      { 
       classLoader = null; 
       i++; 
      } 

      if (i == 3) 
      { 
       throw new Exception("IF failed throw message third time"); 
      } 
     }