下面是我的代码示例:
class foo extends afoo{
@HTTPPost
returnClass runTransaction(RequestData req){
return sendData(req, returnClass.class)
}
@HTTPGet
returnClass runTransaction2(RequestData req){
return sendData(req, returnClass.class)
}
}
abstract class afoo {
public <T> T sendData(ARestMessage req, Class<T> returnClassType)
//here i need the annotation of the calling method
}
基本上,我正在构建一个相当复杂的消息传递系统,并且我希望尽可能多地将切换和配置放在注释中。
是的,我知道有几个库(比如Google reflection)可以让这一切变得更容易,但为了让我使用它们,我必须做4-6个月的书面工作和与企业架构的会议,以获得使用它们的批准。看到这个项目必须在两个月内完成,我正在手工完成它。
所以我要做的是创建注解,开发人员可以用来注解方法,指示结果服务期望发送数据的方式。可以是get、post、put等。在抽象类中,所有服务类都扩展为senddata方法。该方法必须能够找出使用哪个方法调用它,也就是说,是由runTransaction还是runTransaction2调用它,因此sendData提取方法注释,从而准确地知道如何将数据发送到服务。
现在我找到了这个(这是我的sendData方法中的第一行代码)
final Method callingMethod = this.getClass().getEnclosingMethod();
但是它一直返回null。我已经多次阅读了它的javadoc代码,我不明白为什么它总是返回null。
我知道我可以让父调用者使用堆栈,但我不希望这样做,因为此应用程序与执行大量AOP工作的另一个应用程序共享应用程序服务器内存。AOP的工作真的很擅长以非预期的方式搞乱堆栈,所以我宁愿使用直接反射来解决这个问题。
有人知道为什么这个方法总是返回null吗?是不是因为它包含在一个抽象类中,而不是我的foo类本身?有没有办法使用我喜欢使用的技术来实现这一点?
谢谢
发布于 2013-02-23 05:59:52
Class.getEnclosingMethod()
方法并不做您认为它做的事情。下面是它的Javadoc:
如果此类对象表示方法中的本地类或匿名类,则返回表示基础类的直接封闭方法的方法对象。返回null,否则返回。特别是,如果基础类是直接由类型声明、实例初始值设定项或静态初始值设定项包围的局部类或匿名类,则此方法返回null。
具体地说,它返回匿名内部类的外部封闭方法,该方法在该方法的上下文中定义。我在你的描述中没有看到这些消息传递方法是从匿名/本地内部类调用的。下面是一个代码示例(需要jUnit):
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
interface Introspector {
public Method getEnclosingMethod();
}
public class Encloser {
public Encloser() {
super();
}
public Method noop() {
final Introspector inner = new Introspector() {
@Override
public Method getEnclosingMethod() {
return getClass().getEnclosingMethod();
}
};
return inner.getEnclosingMethod();
}
@Test
public void testEnclosingMethods() throws Exception {
final Encloser encloser = new Encloser();
Method method = encloser.getClass().getEnclosingMethod();
Assert.assertNull(method);
method = encloser.noop();
Assert.assertNotNull(method);
}
}
您当前的解决方案听起来相当复杂。您是否计划沿着方法调用链向上移动(这只能通过转储stacktrace btw来实现),并在做了一些繁重的反射之后寻找注释?我预见到了很多bug。坦率地说,使用某种构建器模式可能更适合您的场景。
发布于 2013-02-23 06:43:37
这里使用注释没有意义,只需将另一个参数传递给sendData()
方法即可。
https://stackoverflow.com/questions/15033845
复制相似问题