Using 'getAndRename' method of ClassPool, we can reads a class file and constructs a CtClass object with a new name.
Example
CtClass pointClass = classPool.getAndRename("com.sample.app.model.Point", "com.sample.app.model.MyPoint");
Class<?> MyPointClass = pointClass.toClass();
Object obj = MyPointClass.newInstance();
Find the below working application.
Point.java
package com.sample.app.model;
public class Point {
public int x;
public int y;
}
App.java
package com.sample.app;
import java.lang.reflect.Field;
import com.sample.app.model.Point;
import javassist.ClassPool;
import javassist.CtClass;
public class App {
public static boolean set(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
@SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return (V) field.get(object);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return null;
}
public static void main(String args[]) throws Exception {
ClassPool classPool = ClassPool.getDefault();
CtClass pointClass = classPool.getAndRename("com.sample.app.model.Point", "com.sample.app.model.MyPoint");
Class<?> MyPointClass = pointClass.toClass();
System.out.println(MyPointClass.getName());
Object obj = MyPointClass.newInstance();
set(obj, "x", 10);
set(obj, "y", 20);
Object valueOfX = get(obj, "x");
Object valueOfY = get(obj, "y");
System.out.println("Value of x is : " + valueOfX);
System.out.println("Value of y is : " + valueOfY);
Point point = new Point();
point.x = 123;
point.y = 124;
System.out.println("Value of x is : " + point.x);
System.out.println("Value of y is : " + point.y);
}
}
Run App.java, you will see below messages in console.
com.sample.app.model.MyPoint
Value of x is : 10
Value of y is : 20
Value of x is : 123
Value of y is : 124
No comments:
Post a Comment