1 Reply Latest reply: Sep 21, 2011 1:14 PM by Troy Heninger RSS

Class loader issue in javassist

blalls asdsd Novice

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

 

 

 

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();
    }
}

 

Trying to run, I get this error:

 

 

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)

 

 

 

 

Can anybody help me out please?