1 Reply Latest reply on Sep 21, 2011 1:14 PM by troyhen

    Class loader issue in javassist

    armita

      I am trying to get a hold on javassist for one of our companies projects. I wrote this simple class for testing

       

       

       

      {code}

      public class Main {

          public void test(){

              ClassPool cp = ClassPool.getDefault();

       

       

              CtClass entity = cp.makeClass("Entity");

              try {

                  entity.addField(CtField.make(" public Integer id;",entity));

                  entity.addField(CtField.make(" public String name;", entity));

                  entity.addMethod(CtNewMethod.make("public void say() { System.out.println(12222);}",entity));

                  Class EntityClass = entity.toClass();

                  entity.writeFile("/tmp");

                  Object e=  EntityClass.newInstance();

                  Field name = EntityClass.getField("name");

                  name.set("Ooldooz", e);

                  System.out.println(name.get(e));

              } catch (CannotCompileException e) {

                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

              } catch (InstantiationException e) {

                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

              } catch (IllegalAccessException e) {

                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

              } catch (NoSuchFieldException e) {

                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

              } catch (IOException e) {

                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

              }

          }

          public static void main(String[] args){

              Main main = new Main();

              main.test();

          }

      }{code}

       

      Trying to run, I get this error:

       

      {quote}

      Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.String field Entity.name to java.lang.String

                at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)

                at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)

                at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:37)

                at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:57)

                at java.lang.reflect.Field.set(Field.java:657)

                at Main.test(Main.java:26)

      {quote}

       

       

      Can anybody help me out please?