Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Created December 9, 2018 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhewedy/7345403cfa52e6f47563f8a204ec0e80 to your computer and use it in GitHub Desktop.
Save mhewedy/7345403cfa52e6f47563f8a204ec0e80 to your computer and use it in GitHub Desktop.
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