差異處
這裏顯示兩個版本的差異處。
java:guava:reflections:newproxy [2016/04/13 22:32] tony [How to?] |
java:guava:reflections:newproxy [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>java guava}} | ||
- | ====== Reflection.newProxy ====== | ||
- | ===== Introduction ===== | ||
- | 傳統方法要針對某一個類別中的方法做特殊處理(前處理或後處理),通常我們會將其覆寫或透過Proxy Pattern方式;現今甚至可以透過AOP方式,去達到我們的目的。Guava提供簡便的Dynamic Proxy,讓我們可以針對某"介面"所宣告的method做處理。 | ||
- | ===== How to? ===== | ||
- | 我透過以下類別為範例做解說: | ||
- | <code java> | ||
- | interface TestClassInterface { | ||
- | int test1(); | ||
- | int test2(); | ||
- | } | ||
- | public class TestClass implements TestClassInterface { | ||
- | public int test1(){ | ||
- | System.out.println("test1"); | ||
- | return 1; | ||
- | } | ||
- | |||
- | public int test2(){ | ||
- | System.out.println("test2"); | ||
- | return 2; | ||
- | } | ||
- | } | ||
- | </code> | ||
- | 我想針對TestClass的test2方法做後製,將它的結果+1,以下為我的程式碼: | ||
- | <code java> | ||
- | @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> | ||
- | 從程式碼得知,要做後製的方法可以透過method.getName去處理;不需要的部分則按照原方法呼叫就可以了。 | ||
- | ===== Resource ===== | ||
- | * [[http://n3integration.com/2015/09/23/instrument-java-classes/|Guava - Reflection.newProxy]] | ||
- | ===== ===== | ||
- | ---- | ||
- | \\ | ||
- | ~~DISQUS~~ |