Created
October 2, 2016 11:28
-
-
Save RaffaeleSgarro/410e6e77d08219f7054b9fbccce3c0cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stackoverflow; | |
import javassist.*; | |
public class JavassistVerifyError { | |
public interface Domain { | |
Integer getIdentifier(); | |
Object getColumnByIndex(int i); | |
} | |
public static void main(final String[] args) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException { | |
final ClassPool pool = ClassPool.getDefault(); | |
final CtClass cc = pool.makeClass("Person"); | |
cc.addInterface(resolveCtClass(Domain.class)); | |
final CtField idField = new CtField(resolveCtClass(Integer.class), "id", cc); | |
final CtMethod idGetter = CtNewMethod.getter("getId", idField); | |
final CtMethod idSetter = CtNewMethod.setter("setId", idField); | |
cc.addField(idField); | |
cc.addMethod(idGetter); | |
cc.addMethod(idSetter); | |
final CtField firstNameField = new CtField(resolveCtClass(String.class), "firstName", cc); | |
final CtMethod firstNameGetter = CtNewMethod.getter("getFirstName", firstNameField); | |
final CtMethod firstNameSetter = CtNewMethod.setter("setFirstName", firstNameField); | |
cc.addField(firstNameField); | |
cc.addMethod(firstNameSetter); | |
cc.addMethod(firstNameGetter); | |
final CtMethod getIdentifier = CtNewMethod.make("public Integer getIdentifier () { return id; }", cc); | |
cc.addMethod(getIdentifier); | |
final CtMethod getColumnByIndex = CtNewMethod.make( | |
"public Object getColumnByIndex(int i) {" | |
+ "switch (i) {" | |
+ "case 0:" | |
+ "return id;" | |
+ "case 1:" | |
+ "return firstName;" | |
+ "default: " | |
+ "throw new IllegalArgumentException(\"Tried getting column index i, but this column index does not exist\");" | |
+ "}" | |
+ "}" | |
, cc); | |
cc.addMethod(getColumnByIndex); | |
final Class<?> dynamicClass = cc.toClass(); | |
final Domain domainImpl = (Domain) dynamicClass.newInstance(); | |
System.out.println(domainImpl.getIdentifier()); | |
System.out.println(domainImpl.getColumnByIndex(0)); | |
} | |
private static CtClass resolveCtClass(final Class<?> clazz) throws NotFoundException { | |
final ClassPool pool = ClassPool.getDefault(); | |
return pool.get(clazz.getName()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment