差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

下次修改
前次修改
java:guava:reflections:newproxy [2016/04/13 13:39]
tony 建立
java:guava:reflections:newproxy [2023/06/25 09:48] (目前版本)
行 2: 行 2:
 ====== Reflection.newProxy ====== ====== Reflection.newProxy ======
 ===== Introduction ===== ===== Introduction =====
-傳統方法中,要針對某一個類別中的方法做特殊處理,通常我們會將其覆寫或透過Proxy Pattern方式;現今甚至可以透過AOP方式,去達到我們的目的。Guava提供的是簡便的Dynamic Proxy方式+傳統方法要針對某一個類別中的方法做特殊處理(前處理或後處理),通常我們會將其覆寫或透過Proxy Pattern方式;現今甚至可以透過AOP方式,去達到我們的目的。Guava提供簡便的Dynamic Proxy,讓我們可以針對某"​介面"​所宣告的method做處理
 ===== How to? ===== ===== How to? =====
 +我透過以下類別為範例做解說:​
 <code java> <code java>
-package org.tonylin.practice.guava.reflection;​ +interface TestClassInterface { 
- + int test1()
-import java.lang.reflect.Method+ int test2()
- +} 
-import org.junit.Assert;​ +public class TestClass implements ​TestClassInterface { 
-import org.junit.Test;​ + public ​int test1(){ 
- + System.out.println("​test1"​)
-import com.google.common.reflect.Reflection+ return 1;
- +
-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(){ + public int test2(){ 
- System.out.println("​test2"​);​ + System.out.println("​test2"​);​ 
- return 2; + return 2;
- }+
  }  }
-  +
- @Test +</​code>​ 
- public void testNewProxy(){ +我想針對TestClass的test2方法做後製,將它的結果+1,以下為我的程式碼:​ 
- TestClass tc = new TestClass();​ +<code java> 
- TestClassInterface tci= Reflection.newProxy(TestClassInterface.class,​ +@Test 
- (Object proxy, Method method, Object[] args)->{+public void testNewProxy(){ 
 + TestClass tc = new TestClass();​ 
 + TestClassInterface tci= Reflection.newProxy(TestClassInterface.class,​ 
 + (Object proxy, Method method, Object[] args)->{
   
- if( method.getName().equals("​test2"​) ) { + if( method.getName().equals("​test2"​) ) { 
- return (int)method.invoke(tc,​ args)+1; + return (int)method.invoke(tc,​ args)+1; 
- +
- System.out.println("​proxy"​);​ + System.out.println("​proxy"​);​ 
- return method.invoke(tc,​ args); + return method.invoke(tc,​ args); 
- });+ });
   
- System.out.println("​execute:​ "); + System.out.println("​execute:​ "); 
- Assert.assertEquals(1,​ tci.test1());​ + Assert.assertEquals(1,​ tci.test1());​ 
- Assert.assertEquals(3,​ tci.test2());​ + Assert.assertEquals(3,​ tci.test2());​
-+
- +
 } }
 </​code>​ </​code>​
 +從程式碼得知,要做後製的方法可以透過method.getName去處理;不需要的部分則按照原方法呼叫就可以了。\\ 
 +\\ 
 +Output: 
 +<​code>​ 
 +execute:  
 +proxy 
 +test1 
 +test2 
 +</​code>​
 ===== Resource ===== ===== Resource =====
   * [[http://​n3integration.com/​2015/​09/​23/​instrument-java-classes/​|Guava - Reflection.newProxy]]   * [[http://​n3integration.com/​2015/​09/​23/​instrument-java-classes/​|Guava - Reflection.newProxy]]