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

 

你可能感兴趣的:(annotation)