差異處
這裏顯示兩個版本的差異處。
java:guava:reflections:newproxy [2016/04/13 13:39] tony 建立 |
java:guava:reflections:newproxy [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>java guava}} | ||
- | ====== Reflection.newProxy ====== | ||
- | ===== Introduction ===== | ||
- | 在傳統方法中,要針對某一個類別中的方法做特殊處理,通常我們會將其覆寫或透過Proxy Pattern方式;現今甚至可以透過AOP方式,去達到我們的目的。而Guava提供的是簡便的Dynamic Proxy方式。 | ||
- | ===== How to? ===== | ||
- | <code java> | ||
- | package org.tonylin.practice.guava.reflection; | ||
- | import java.lang.reflect.Method; | ||
- | |||
- | import org.junit.Assert; | ||
- | import org.junit.Test; | ||
- | |||
- | import com.google.common.reflect.Reflection; | ||
- | |||
- | public class TestReflection { | ||
- | |||
- | interface TestClassInterface { | ||
- | int test1(); | ||
- | int test2(); | ||
- | } | ||
- | |||
- | public static class TestClass implements TestClassInterface { | ||
- | public int test1(){ | ||
- | System.out.println("test1"); | ||
- | return 1; | ||
- | } | ||
- | |||
- | public int test2(){ | ||
- | System.out.println("test2"); | ||
- | return 2; | ||
- | } | ||
- | } | ||
- | |||
- | @Test | ||
- | public void testNewProxy(){ | ||
- | TestClass tc = new TestClass(); | ||
- | TestClassInterface tci= Reflection.newProxy(TestClassInterface.class, | ||
- | (Object proxy, Method method, Object[] args)->{ | ||
- | |||
- | if( method.getName().equals("test2") ) { | ||
- | return (int)method.invoke(tc, args)+1; | ||
- | } | ||
- | System.out.println("proxy"); | ||
- | return method.invoke(tc, args); | ||
- | }); | ||
- | |||
- | System.out.println("execute: "); | ||
- | Assert.assertEquals(1, tci.test1()); | ||
- | Assert.assertEquals(3, tci.test2()); | ||
- | } | ||
- | |||
- | } | ||
- | </code> | ||
- | |||
- | ===== Resource ===== | ||
- | * [[http://n3integration.com/2015/09/23/instrument-java-classes/|Guava - Reflection.newProxy]] | ||
- | |||
- | ===== ===== | ||
- | ---- | ||
- | \\ | ||
- | ~~DISQUS~~ |