New file |
0,0 → 1,65 |
package jomm.experiments; |
|
import javassist.util.proxy.MethodFilter; |
import javassist.util.proxy.MethodHandler; |
import javassist.util.proxy.ProxyFactory; |
import pt.estgp.estgweb.domain.User; |
|
import java.lang.reflect.InvocationTargetException; |
import java.lang.reflect.Method; |
|
/** |
* Created by jorgemachado on 12/04/16. |
*/ |
public class JavaAssistDynamicProxy |
{ |
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { |
|
|
ProxyFactory factory = new ProxyFactory(); |
factory.setSuperclass(User.class); |
factory.setFilter( |
new MethodFilter() { |
@Override |
public boolean isHandled(Method method) { |
return true; |
//return Modifier.isAbstract(method.getModifiers()); |
} |
} |
); |
|
|
MethodHandler handler = new MethodHandler() { |
@Override |
public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { |
System.out.println("Handling " + thisMethod + " via the method handler"); |
if(thisMethod.getName().startsWith("getId")) |
{ |
return proceed.invoke(self,args); |
} |
else if(thisMethod.getName().startsWith("get")) |
{ |
System.out.println("Acedendo a uma propriedade " + thisMethod.getName() + " na class " + thisMethod.getDeclaringClass().getName()); |
String campo = thisMethod.getName().substring(3); |
campo = ("" + campo.charAt(0)).toLowerCase() + campo.substring(1); |
System.out.println("select " + campo + " from " + thisMethod.getDeclaringClass().getCanonicalName() + " where id = " + |
self.getClass().getMethod("getId").invoke(self,new Object[]{})); |
} |
if(thisMethod.getName().startsWith("set")) |
{ |
System.out.println("Alterando uma propriedade no proxy " + thisMethod.getName() + " na class " + thisMethod.getDeclaringClass().getName()); |
return proceed.invoke(self,args); |
} |
return null; |
} |
}; |
|
User u = (User) factory.create(new Class[0], new Object[0], handler); |
u.setId(3); |
|
u.getUsername(); |
u.getCourses(); |
u.getId(); |
|
} |
} |