CtClass.toClass抛出一个异常消息'null'

时间:2011-07-11 05:59:10

标签: java javassist

我执行创建动态类的步骤如下:

      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 个答案:

答案 0 :(得分: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");
            }
        }