通过Annotation实现对程序的运行状态监听,简单实现

来源:互联网 发布:plc触摸屏编程实例 编辑:程序博客网 时间:2024/05/30 22:58


import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


import javax.swing.AbstractButton;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JPanel;


import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

import java.lang.reflect.Field;


@Target (ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)//运行时调用

 @interfaceActionListenerFor {

Class<? extends ActionListener> listener();

}


public class AnnotationTest {

private JFramemainWin = new JFrame("使用注释绑定事件监听器");

@ActionListenerFor(listener = OkListener.class)

private JButtonok = new JButton("确定");

@ActionListenerFor(listener = CancelListener.class)

private JButtoncancel = new JButton("取消");

publicvoid init(){

//初始化界面的方法

JPanel jp =new JPanel();

jp.add(ok);

jp.add(cancel);

mainWin.add(jp);

ActionListenerInstaller.processAnnotation(this);

mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

mainWin.pack();

mainWin.setVisible(true);

}

publicstatic void main(String[] args){

new AnnotationTest().init();

}

}

class ActionListenerInstaller{

publicstatic void processAnnotation(Object obj){

try{

Classc1 = obj.getClass();

for (Fieldf:c1.getDeclaredFields()) {

//将制定field设定为可以自由访问

f.setAccessible(true);

//获取指定类型的annotation

ActionListenerFora = f.getAnnotation(ActionListenerFor.class);

//获取f Field实际对应的对象

Object fObj =f.get(obj);

//如果f是Abstractbutton,则a!=null

if (a !=null && fObj != null && fObj instanceof AbstractButton) {

Class< ? extends ActionListener>listenerClazz = a.listener();

//使用反射来创建listener类的对象

ActionListener a1 =listenerClazz.newInstance();

AbstractButton ab = (AbstractButton)fObj;

//为ab添加事件监听器

ab.addActionListener(a1);

}

}

}catch (Exceptione){

e.printStackTrace();

}

}

}



class OkListener implements ActionListener{

publicvoid actionPerformed(ActionEventevt){

JOptionPane.showMessageDialog(null,"单击了确认按钮");

}

}


//定义cancel按钮的事件监听器实现类

class CancelListener implements ActionListener{

publicvoid actionPerformed(ActionEventevt){

JOptionPane.showMessageDialog(null,"单击了取消按钮");

}

}


0 0
原创粉丝点击