首先创建一个注解,目前只实现了一个点击事件,其他的原理相同
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OpActionListener { String value(); }
package com.demo.inject; import com.demo.annotation.OpActionListener; import java.awt.event.ActionListener; import java.lang.reflect.*; /** * User: jay.zhoujingjie * Date: 14-2-17 * Time: 下午5:18 */ public class ActionListenerAttach { private Object obj; public ActionListenerAttach(Object obj){ this.obj =obj; for(Method method: obj.getClass().getDeclaredMethods()){ OpActionListener ann = method.getAnnotation(OpActionListener.class); if(ann != null){ String value = ann.value(); try { Field field = obj.getClass().getDeclaredField(value); if(!field.isAccessible()){ field.setAccessible(true); addListener(field.get(obj),method); } } catch (Exception e) { e.printStackTrace(); } } } } public void addListener(final Object source,final Method m) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Object listener = Proxy.newProxyInstance(obj.getClass().getClassLoader(),new Class[]{ActionListener.class},new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(m.getParameterTypes().length == 0){ return m.invoke(obj); } return m.invoke(obj,args); } }); source.getClass().getMethod("addActionListener",ActionListener.class).invoke(source, listener); } }
public class LoginFrame extends ParentFrame { private JTextField tfName; private JPasswordField pfPass; private JButton btnLogin; public LoginFrame() { initUI(); new ActionListenerAttach(this); } private void initUI() { Container container = this.getContentPane(); this.setLayout(new GridBagLayout()); container.add(new JLabel("用户名:"), gbc(0, 0, 1, 1)); container.add(tfName = new JTextField(10), gbc(1, 0, 3, 1)); container.add(new JLabel("密 码:"), gbc(0, 1, 1, 1)); container.add(pfPass = new JPasswordField(10), gbc(1, 1, 3, 1)); container.add(btnLogin = new JButton("登陆"), gbc(1, 2, 2, 1)); this.setSize(200, 150); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setVisible(true); } @OpActionListener("btnLogin") public void click(){ JOptionPane.showMessageDialog(null, tfName.getText() + "\n" + String.valueOf(pfPass.getPassword())); } @OpActionListener("btnLogin") public void click(ActionEvent event){ JOptionPane.showMessageDialog(null, tfName.getText() + "\n" + String.valueOf(pfPass.getPassword())); } }
原文:http://blog.csdn.net/sc_jelly/article/details/19345989