编程语言
首页 > 编程语言> > java协助新手问题

java协助新手问题

作者:互联网

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

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

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

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)

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

解决方法:

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

你反过来称呼它.

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

标签:java,javassist
来源: https://codeday.me/bug/20190704/1379992.html