19. december 2009 - 14:28Der er
3 kommentarer og 1 løsning
AOP - Java-proxy
Hi,
jeg vil gerne vide om det er muligt at lave noget som AOP-programmering med plain java (java-6).
jeg kan finde pages på nettet, som bruger noget som Proxy.getProxyClass(...)
men jeg kan ikke finde et executeable eksempel, som jeg kan teste rundt med. Er der nogen som kan lave hjelpe med et eksempel? ---------------------------------------------------- public class TestClass { public void dummyOutput() { System.out.println( "dummy output" ); } } ---------------------------------------------------- public class TestProxy extends ??? implements ??? { public void executeBefore( Class classType, Method method, Object[] params ) { if ( classType instanceof TestClass ) { System.out.println( "trace -> run method: "+method.getName() ); } ... } ... } ---------------------------------------------------- public class Main { public static void main( String[] args ) { // Proxy.initClass( // TestClass.class, // TestClass.class.getClassLoader() );
TestClass testClass = new TestClass(); testClass.dummyOutput(); } } ----------------------------------------------------
public class ProxyFun { public static void main(String[] args) { Test orig = new TestImpl(); orig.dummyOutput(); Test tst = (Test) Proxy.newProxyInstance(orig.getClass().getClassLoader(), orig.getClass().getInterfaces(), new AOP(orig)); tst.dummyOutput(); }
}
interface Test { public void dummyOutput(); }
class TestImpl implements Test { public void dummyOutput() { System.out.println( "dummy output" ); } }
class AOP implements InvocationHandler { private Object obj; public AOP(Object o) { this.obj = o; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println( "trace -> run method: " + method.getName()); return method.invoke(obj, args); } }
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.