`
hpgary
  • 浏览: 78688 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

动态代理--接口无实现可以调用

    博客分类:
  • Java
 
阅读更多

模仿Mybatis,只有接口创建代理实现,根据方法名调用调用实现:参考MyBatis源码类:

MapperProxyFactory, MapperProxy 

创建接口类:

public interface MethodInterface {
	String helloWorld();
}

 

动态代理类:

 

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MethodProxy<T> implements InvocationHandler {

	protected Class<T> methodInterface;

	public MethodProxy(Class<T> methodInterface) {
		this.methodInterface = methodInterface;
	}
	
	public static void main(String[] args) {
		MethodInterface newInstance = newInstance(MethodInterface.class);
		System.out.println( newInstance.helloWorld() );
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T newInstance(Class<T> methodInterface) {
		final MethodProxy<T> methodProxy = new MethodProxy<T>(methodInterface);
		return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
				new Class[] { methodInterface }, methodProxy);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("方法名:" + method.getName()); 
		// 针对不同的方法进行不同的操作
		if (method.getName().equalsIgnoreCase("helloWorld")){
			return "世界你好" ;
		}
		return null; 
	}
	
}

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics