java assist newbie question
I am trying to generate some classes on the fly, and the following is my initial attempt:
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();
}
But I face a class loader issue:
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)
Any ideas on how can I resolve this?
Field#set takes the object as the first parameter and the value as the second.
You are calling it the other way around.
Change it to name.set(e, "Ooldooz");
精彩评论