那么它可能不是最好的,甚至正确的方式,但我的第一个猜测是使用当前的堆栈跟踪,似乎为我工作:
package yourpackage;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AspectJRawTest {
public static void main(String[] args) {
System.out.println("custom annotation playground");
ISomething something = new SomethingImpl();
something.annotatedMethod();
something.notAnnotatedMethod();
}
}
interface ISomething {
void annotatedMethod();
void notAnnotatedMethod();
}
class SomethingImpl implements ISomething {
@MyCustomAnnotation
public void annotatedMethod() {
System.out.println("I am annotated and something must be printed by an advice above.");
CalledFromAnnotatedMethod ca = new CalledFromAnnotatedMethod();
}
public void notAnnotatedMethod() {
System.out.println("I am not annotated and I will not get any special treatment.");
CalledFromAnnotatedMethod ca = new CalledFromAnnotatedMethod();
}
}
/**
* Imagine this is your bean which needs to know if any annotations affected it's construction
*/
class CalledFromAnnotatedMethod {
CalledFromAnnotatedMethod() {
List<Annotation> ants = new ArrayList<Annotation>();
for (StackTraceElement elt : Thread.currentThread().getStackTrace()) {
try {
Method m = Class.forName(elt.getClassName()).getMethod(elt.getMethodName());
ants.addAll(Arrays.asList(m.getAnnotations()));
} catch (ClassNotFoundException ignored) {
} catch (NoSuchMethodException ignored) {
}
}
System.out.println(ants);
}
}
输出清楚地表明,我得到了一个访问我的对象的构造函数中的注释从注释方法中调用时:
custom annotation playground
I am annotated and something must be printed by an advice above.
[@yourpackage.MyCustomAnnotation(isRun=true)]
I am not annotated and I will not get any special treatment.
[]
什么意思是“某事”?您的注释是运行时保留注释吗? “MyBean”是否有关于“MyConfig”的任何信息,或者您是否期望它知道注释而不知道是什么称呼它? – RealSkeptic
@RealSkeptic(1)“something”意思是注解的存在和它的参数。 (2)注释和所需的一样“好”,它绝对是运行时(3)否(4)我期望可能是Spring,当从注释配置实例化bean时,从注释中获取一些信息, – Dims