java 反射问题求教

我现在正在做一个简单的框架性质的东西,设计的调用该框架的示例代码如下:


@A("xxx")public class  App{    public static void main(String[] args){
        B.run();
    }
}


其中类App是框架用户自定义的类,他在main方法中调用了框架的API,并通过注解A配置了相关参数,因此我想在run方法中去取得注解A配置的值,请问该如何获取到呢?

 

ps:肯定是能拿到的,因为SpringBoot就有类似的设计(实际上我的这种想法就是借鉴的SpringBoot)


HUX布斯
浏览 548回答 1
1回答

陪伴而非守候

解决方案:1. 让用户自己将class对象传进来2. 使用:StackTraceElement[]&nbsp;stackTrace&nbsp;=&nbsp;Thread.currentThread().getStackTrace(); Class<?>&nbsp;mainClass&nbsp;=&nbsp;null;if&nbsp;(stackTrace.length&nbsp;!=&nbsp;0)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;StackTraceElement&nbsp;traceElement&nbsp;=&nbsp;stackTrace[stackTrace.length&nbsp;-&nbsp;1];&nbsp;&nbsp;&nbsp;&nbsp;try&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mainClass&nbsp;=&nbsp;Class.forName(traceElement.getClassName()); &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;catch&nbsp;(ClassNotFoundException&nbsp;e)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;LOGGER.warn(e.toString()); &nbsp;&nbsp;&nbsp;&nbsp;} }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java