這是本文件的舊版!


Reflection.newProxy

在傳統方法中,要針對某一個類別中的方法做特殊處理,通常我們會將其覆寫或透過Proxy Pattern方式;現今甚至可以透過AOP方式,去達到我們的目的。而Guava提供的是簡便的Dynamic Proxy方式。

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());
	}
 
}