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 ran into a class loader problem:
An exception in the "main" thread java.lang.IllegalArgumentException: cannot set the java.lang.String Entity.name field for java.lang.String at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException (UnsafeFieldAccessorImpl.java:146.Unsafereplfafefrefafeflafefrefafe ... Field.java:657) on Main.test (Main.java:26)
Any ideas on how I can solve this?
source share