Create class with javassist and make it available

后端 未结 2 597
逝去的感伤
逝去的感伤 2021-01-15 21:03

I want to do the following:

try {
    Class.forName(\"MyClass\");
} catch(ClassNotFoundException e) {
    ClassPool pool = ClassPool.getDefault();
    CtClas         


        
相关标签:
2条回答
  • 2021-01-15 21:44

    I found out that my code was creating the class on different classloaders depending where I was calling it from. I solved this by doing the following:

    try {
        Class.forName("MyClass");
    } catch(ClassNotFoundException e) {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.makeClass("MyClass");
        cc.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain());
        Class.forName("MyClass");
    }
    

    Calling the toClass method with the proper Classloader did the trick... I was just unsure on how to control on what classloader the created class would become available, but the method with the classloader parameters allows exactly what I was looking for.

    0 讨论(0)
  • 2021-01-15 21:57
    `try {
        Class.forName("MyClass");
    } catch(ClassNotFoundException e) {
    try {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.makeClass("MyClass");
        Class.forName("MyClass");
    catch(Exception e) {
    }
    }`
    

    Check with this code, sometime jvm optimize the code and shuffle the statements , except in try block.

    0 讨论(0)
提交回复
热议问题