简体   繁体   English

为 java.io.FileOutputStream 编写 aspectj 切入点

[英]Writing an aspectj pointcut for java.io.FileOutputStream

I would like to write a pointcut for the new FileInputstream(File file) constructor.我想为new FileInputstream(File file)构造函数写一个切入点。 For example, a common way to create a new file in java is:例如,在 java 中创建新文件的常用方法是:

File file = new File(myDirectory, "myFileName.txt");
new FileOutputStream(file);

What I've tried so far is this:到目前为止,我尝试过的是:

Inside FileCreation.aj :FileCreation.aj

import java.io.File;
import java.io.FileOutputStream;

aspect FileCreation {

    pointcut FileOutputStream1(File file): call(FileOutputStream FileOutputStream(File)) && args(file);
    FileOutputStream around(File file): FileOutputStream1(file) {
        System.out.println("I was called!!");
        return proceed(file);
    }

}

In order to test whether this hook is working, I added a print statement.为了测试这个钩子是否工作,我添加了一个打印语句。

However, it seems like this isn't getting invoked.但是,这似乎没有被调用。

Not sure what the mistake is in this case.不知道在这种情况下错误是什么。

The problem is invalid constructor call syntax.问题是无效的构造函数调用语法。 You need to use .new and no return type specifier, because the return type implicitly is always the class of the intercepted constructor.您需要使用.new并且没有返回类型说明符,因为返回类型隐式始终是被拦截的构造函数的 class 。

BTW, be careful not to name methods like classes.顺便说一句,注意不要将方法命名为类。 Better use fileOutputStream1 with a lower-case "f" as a pointcut name.最好使用带有小写“f”的fileOutputStream1作为切入点名称。 Otherwise, your code is difficult to read.否则,您的代码很难阅读。

package de.scrum_master.aspect;

import java.io.File;
import java.io.FileOutputStream;

aspect FileCreation {
  pointcut fileOutputStream1(File file) :
    call(FileOutputStream.new(File)) &&
    args(file);

  FileOutputStream around(File file) : fileOutputStream1(file) {
    System.out.println("I was called!!");
    return proceed(file);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM