/* * Copyright (C) 2011 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * @author <a href="hoang281283@gmail.com">Minh Hoang TO</a> * @date 7/8/11 */ public class TestUsingProxy { public interface Foo { public void bar(); } public class Decorator implements Foo { private Foo decoratedObject; public Decorator(Foo foo) { this.decoratedObject = foo; } public void bar() { System.out.println("Calling bar() from Decorator"); decoratedObject.bar(); } } public class CustomDecorator extends Decorator { public CustomDecorator(Foo foo) { super(foo); } public void bar() { System.out.println("Calling bar() from CustomDecorator"); super.bar(); } } public static void main(String[] args) throws Exception { InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Executing the handler method why invoking method: " + method.getName() + " on proxy"); return null; } }; Class<? extends Proxy> proxyClazzForFoo = Proxy.getProxyClass(Thread.currentThread().getContextClassLoader(), Foo.class).asSubclass(Proxy.class); Foo fooCreatedByProxy = (Foo)proxyClazzForFoo.getConstructor(InvocationHandler.class).newInstance(handler); TestUsingProxy test = new TestUsingProxy(); test.new CustomDecorator(test.new Decorator(fooCreatedByProxy)).bar(); } }