`
zhaole609
  • 浏览: 339560 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类
最新评论

annotation,反射,动态代理小例

 
阅读更多

 

 

 

代理过于简单,不解释了

 

package activebind;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import zhaole609.BindClass;

import myannotation.MyProperty;

public class ButtonFrame extends JFrame {
	
	@MyProperty
	private JButton blueButton=new JButton("blue");
	
	@MyProperty
	private JButton redButton=new JButton("red");
	
	@MyProperty
	private JButton greenButton=new JButton("green");
	
	private JPanel  panel;
	
	private JPanel bpanel;
	public ButtonFrame(){
	 
		panel=new JPanel();
		bpanel=new JPanel();
		panel.setSize(300,200);
		panel.setBackground(Color.blue);
		this.getContentPane().setLayout(new BorderLayout());
		this.add(panel,BorderLayout.CENTER);
		this.add(bpanel,BorderLayout.SOUTH);
		bpanel.add(blueButton);
		bpanel.add(redButton);
		bpanel.add(greenButton);
		this.setSize(300,300);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		changeBackGround();
	}
	public void changeBackGround(){
		try {
			BindClass.LookupAndBindFieldMethoid(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		new ButtonFrame();
	}
}

 package myannotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyProperty {
}

 package zhaole609;

import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import myannotation.MyProperty;

public class BindClass {
	public static void LookupAndBindFieldMethoid(Object o) throws Exception{
		 
		Field[] fields=o.getClass().getDeclaredFields();
		for(Field field : fields){
			if(field.getAnnotation(MyProperty.class)!=null){
			    field.setAccessible(true);
				bindMethod(field.get(o));
			}
		}
	}
	
	public static void bindMethod(Object ob) throws Exception{
		InvocationHandler handler=new InvocationHandler(){
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// TODO Auto-generated method stub
				System.out.println("before");
				Object result= method.invoke(proxy,null);
				System.out.println("after");
				return result;
			}
			
		};
		Object proxyObj=Proxy.newProxyInstance(ob.getClass().getClassLoader(),new Class[]{ActionListener.class},handler);
		Method method=ob.getClass().getMethod("addActionListener",new Class[]{ActionListener.class});
		method.invoke(ob,proxyObj);
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics