java辅助新手问题

java辅助新手问题,java,javassist,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);

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

  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 在sun.reflect.UnsafeFieldAccessorImpl.throwsetilegalargumentexception(UnsafeFieldAccessorImpl.java:146)中 在sun.reflect.UnsafeFieldAccessorImpl.throwsetilegalargumentexception(UnsafeFieldAccessorImpl.java:150)处 在sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:37) 位于sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:57) 位于java.lang.reflect.Field.set(Field.java:657) at Main.test(Main.java:26)

有没有办法解决这个问题?

将对象作为第一个参数,值作为第二个参数

你说的是另一种说法

将其更改为
name.set(e,“Ooldooz”)