实现java闭包的另一种形式

记得第一次接触闭包的时候,觉得很奇怪,但从字面上很那理解闭包什么玩意,和闭包有的一比的当属控制反转,真正理解了后觉得就平常了。闭包二字其实是很经典的,闭包代码所表现的东西可不就是一个封闭的、自成一体的功能块吗?简单的说,闭包就是在内部定义的方法,拿到外面去使用。经典的javascript闭包形式如下:

Java代码 复制代码
  1.   

 

Js代码 复制代码
  1. function f1(){   
  2.     var i = 20;   
  3.     function closef(x){   
  4.         alert(i+x);   
  5.     }   
  6.     return closef   
  7.   
  8. }   
  9.   
  10. var s = f1();   
  11. s(20);  

javascript的这种闭包形式的确相当简洁,类似于c语言的函数指针

 众所周知,java实现闭包的形式是内部类,更常用的还是匿名内部类,而这通常还需要定义接口,通过接口的引用来操作内部类对象,从而实现闭包,远没有javascript简洁。这里介绍我在开发中使用的一种java闭包形式,当然还是内部类,我在实现的时候把反射机制加了进来,这么做就是尽量使用起来简单一些。代码如下:

先定义一个接口,接口还是需要的,在以后的闭包使用中,只需要这一个接口。

Java代码 复制代码
  1. package p;   
  2.   
  3. public interface IMethod {   
  4.            
  5.     public Object invoke(Object ... objects );   
  6.   
  7. }  
package p;

public interface IMethod {
		
	public Object invoke(Object ... objects );

}

 

该接口的实现类,这里引入反射:

 

Java代码 复制代码
  1. package p;   
  2.   
  3. import java.lang.reflect.Method;   
  4.   
  5. public class MethodObject implements IMethod {   
  6.        
  7.     private Object target;//闭包所依赖的对象   
  8.        
  9.     private String methodName;//闭包方法的名字   
  10.        
  11.     public MethodObject(){}   
  12.   
  13.     public MethodObject(Object target, String methodName) {   
  14.         super();   
  15.         this.target = target;   
  16.         this.methodName = methodName;   
  17.     }   
  18.   
  19.     public Object invoke(Object... objects) {   
  20.         Class clazz = target.getClass();   
  21.         try {   
  22.             Method[] ms = clazz.getDeclaredMethods();   
  23.                
  24.             Method targetMethod = null;   
  25.             for(Method m : ms){   
  26.                 if(methodName.equals(m.getName())){   
  27.                     targetMethod = m;   
  28.                     break;   
  29.                 }   
  30.             }   
  31.             targetMethod.setAccessible(true);   
  32.             return targetMethod.invoke(target, objects);   
  33.         } catch (Exception e) {   
  34.             // TODO Auto-generated catch block   
  35.             throw new RuntimeException(e);   
  36.         }    
  37.     }   
  38.        
  39.     public void rebund(Object anothertarget){   
  40.         target = anothertarget;   
  41.     }   
  42.        
  43.   
  44. }  
package p;

import java.lang.reflect.Method;

public class MethodObject implements IMethod {
	
	private Object target;//闭包所依赖的对象
	
	private String methodName;//闭包方法的名字
	
	public MethodObject(){}

	public MethodObject(Object target, String methodName) {
		super();
		this.target = target;
		this.methodName = methodName;
	}

	public Object invoke(Object... objects) {
		Class clazz = target.getClass();
		try {
			Method[] ms = clazz.getDeclaredMethods();
			
			Method targetMethod = null;
			for(Method m : ms){
				if(methodName.equals(m.getName())){
					targetMethod = m;
					break;
				}
			}
			targetMethod.setAccessible(true);
			return targetMethod.invoke(target, objects);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} 
	}
	
	public void rebund(Object anothertarget){
		target = anothertarget;
	}
	

}

 

下面是具体使用闭包的形式:

 

Java代码 复制代码
  1. public class Person {   
  2.        
  3.     private int age = 0;   
  4.        
  5.     public Person(int age) {   
  6.         super();   
  7.         this.age = age;   
  8.     }   
  9.   
  10.   
  11.        
  12.        
  13.        
  14.     public IMethod getClosualMethod(){   
  15.            
  16.         final int i = 10;   
  17.            
  18.         Object o = new Object(){   
  19.             Date getBirthday(){   
  20.                 Calendar c = Calendar.getInstance();   
  21.                 c.set(Calendar.YEAR,c.get(Calendar.YEAR) - (age+i));   
  22.                 return c.getTime();   
  23.             }   
  24.         };   
  25.            
  26.         MethodObject mo = new MethodObject(o,"getBirthday");   
  27.         return mo;   
  28.     }   
  29. }  
public class Person {
	
	private int age = 0;
	
	public Person(int age) {
		super();
		this.age = age;
	}


	
	
	
	public IMethod getClosualMethod(){
		
		final int i = 10;
		
		Object o = new Object(){
			Date getBirthday(){
				Calendar c = Calendar.getInstance();
				c.set(Calendar.YEAR,c.get(Calendar.YEAR) - (age+i));
				return c.getTime();
			}
		};
		
		MethodObject mo = new MethodObject(o,"getBirthday");
		return mo;
	}
}

 

Java代码 复制代码
  1. package test;   
  2.   
  3. import p.IMethod;   
  4.   
  5. public class Test {   
  6.   
  7.     /**  
  8.      * @param args  
  9.      */  
  10.     public static void main(String[] args)throws Exception {   
  11.         // TODO Auto-generated method stub   
  12.         Person p = new Person(20);   
  13.            
  14.         IMethod m = p.getClosualMethod();   
  15.         Object o = m.invoke();   
  16.         System.out.println(o);   
  17.            
  18.         IMethod m2 = p.getClosualMethod2();   
  19.         m2.invoke("Tom");   
  20.     }   
  21.        
  22.   
  23. }  
package test;

import p.IMethod;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
		Person p = new Person(20);
		
		IMethod m = p.getClosualMethod();
		Object o = m.invoke();
		System.out.println(o);
		
		IMethod m2 = p.getClosualMethod2();
		m2.invoke("Tom");
	}
	

}

 

 下面是输出结果:

Sun Jun 03 17:35:05 CST 1979
hello Tom, I am 20 years old

 

从这里可以看到,有了Imethod和MethodObject,在java里使用闭包,就可以像javascript那样方便了。当然,这只是模拟,如果想要达到javascript那样在运行期改变对象的属性和方法,可以在更高一级去模拟。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值