java协助新手问题

时间:2011-08-04 16:13:19

标签: java javassist

我正在尝试动态生成一些类,以下是我最初的尝试:

  ClassPool cp = ClassPool.getDefault();
    cp.insertClassPath(new ClassClassPath(Main.class));
    CtClass entity = cp.makeClass("Entity");
    try {
        CtField id = new CtField(CtClass.intType, "id", entity);

        entity.addField(id);
        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();  
    } catch (InstantiationException e) {
        e.printStackTrace();  
    } catch (IllegalAccessException e) {
        e.printStackTrace();  
    } catch (NoSuchFieldException e) {
        e.printStackTrace();  
    } catch (IOException e) {
        e.printStackTrace();  
    }

但是我遇到了类加载器问题:

  

线程“main”中的异常java.lang.IllegalArgumentException:无法将java.lang.String字段Entity.name设置为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)       在java.lang.reflect.Field.set(Field.java:657)       在Main.test(Main.java:26)

关于如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:2)

Field#set将对象作为第一个参数,将值作为第二个参数。

你反过来称呼它。

将其更改为name.set(e, "Ooldooz");