Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use CGLib on final classes
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class TestCGLib {
public static void main(String[] args) {
try {
Person person = createProxy(Person.class);
person.doPrint();
} catch (IllegalArgumentException ex) {
System.out.println(ex);
}
try {
System.out.println("-------------------------");
PersonWithFinalMethods personWithFinalMethods = createProxy(PersonWithFinalMethods.class);
personWithFinalMethods.doPrint();
personWithFinalMethods.finalDoPrint();
} catch (IllegalArgumentException ex) {
System.out.println(ex);
}
try {
System.out.println("-------------------------");
FinalPerson finalPerson = createProxy(FinalPerson.class);
finalPerson.doPrint();
finalPerson.finalDoPrint();
} catch (IllegalArgumentException ex) {
System.out.println(ex);
}
}
@SuppressWarnings("unchecked")
private static <T> T createProxy(Class<T> klass) {
return (T) Enhancer.create(klass, new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("before");
Object o = proxy.invokeSuper(obj, args);
System.out.println("after");
return o;
}
});
}
static final class FinalPerson {
final void finalDoPrint() {
System.out.println("FinalPerson::finalDoPrint");
}
void doPrint() {
System.out.println("FinalPerson::doPrint");
}
}
static class PersonWithFinalMethods {
final void finalDoPrint() {
System.out.println("PersonWithFinalMethods::finalDoPrint");
}
void doPrint() {
System.out.println("PersonWithFinalMethods::doPrint");
}
}
static class Person {
void doPrint() {
System.out.println("Person::doPrint");
}
}
}
//// Output:
/*
before
Person::doPrint
after
-------------------------
before
PersonWithFinalMethods::doPrint
after
PersonWithFinalMethods::finalDoPrint
-------------------------
java.lang.IllegalArgumentException: Cannot subclass final class TestCGLib$FinalPerson
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.