我正在处理一个项目,我的任务是实现一个自定义 Java Swing 库,每当用户与 Swing 组件交互时,该库都会将事件记录到文件中。换句话说,每当用户与 GUI 上的按钮、复选框等交互时,该事件都会记录到文件中。日志条目必须包含事件发生位置的源文件名和行号。有一个问题:对于由库外部的开发人员实现的方法,日志记录机制需要在库中自动发生。能做到吗?这是我到目前为止所拥有的:
自定义库操作监听器:
public abstract class MyActionListener implements ActionListener
{
// Prevents the developer from implementing the "actionPerformed" method
@Override
public final void actionPerformed(ActionEvent e)
{
// Do nothing
}
// Custom method
public void actionPerformed(MyActionEvent e)
{
doCustomMethod();
// Tried obtaining the stack trace here but there's no entry
// in the trace for "doCustomMethod()"
StackTraceElement [] elements = Thread.currentThread().getStackTrace();
for (StackTraceElement element : elements)
{
// print each element
}
}
// Forces the developer to implement this method
public abstract void doCustomMethod();
}
自定义库按钮:
public class MyButton extends JButton
{
...
// Custom method
public void addActionListener(MyActionListener l)
{
listenerList.add(MyActionListener.class, l);
}
}
开发人员创建 GUI:
public class TestGui extends JFrame
{
TestGui()
{
...
MyButton button = new MyButton("Push");
button.addActionListener(new MyActionListener()
{
public void doCustomMethod()
{
// Want to log this line number and file name,
// but need the library to do it; NOT the developer.
}
});
}
}
我已经准备好所有正确的逻辑,以便调用正确的 addActionListener() 和 actionPerformed() 方法。我的问题是尝试记录事件。我也尝试过实现自定义 Java 注释,但没有成功。另外,开发人员必须在构建 GUI 时包含 -processor 选项。我们试图让开发人员像使用 Java Swing 库一样使用我们的自定义 Swing 库。我实现的更改对开发人员来说是透明的。
非常感谢任何帮助。
最佳答案
遍历组件树并将监听器添加到每个组件(JButton 等 - 可以与用户交互并且您需要它)怎么样?
然后开发人员可以使用简单的 JButton(而不是 MyButton)。 但是当您使用这种方法时 - 您应该在创建所有组件后调用遍历组件方法。如果要添加其他组件,您还可以添加监听 Component#add 方法并更新监听器的 ComponentListener。
关于Java:是否可以(在运行时)获取 future 方法调用的源文件名和行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625526/