java 什么情况下是用反射的获取方法

java 什么情况下是用反射的获取方法,第1张

等你学过SSH之后你就明白为要用反射了,牛B的框架都是通过配置文件,即反射机制来做的

例如吧,你想把a对象放到b对象中,但是你并不知道B对象的方法名叫什么

,或者并不知道用户会将方法名定义成什么

这个时候,你只需要在配置文件中,或者是用注解,写上去那么通过反射就可以得到某个方法了

反射机制是比较高级的东西,你还是踏踏实实的吧,

就这么说你可以理解不了,也并不知道他的意义在哪,

只有等你接触的框架,代码多了自然会明白他的作用

你可以这么写:

class BodyImpl implements Body{

//do something

public static void main(String[] args) {

Type[] interfaces = BodyImplclassgetInterfaces();

ParameterizedType firstInterface = (ParameterizedType) interfaces[0];

Class c = (Class) firstInterfacegetActualTypeArguments()[0];

Systemoutprintln(cgetName()); // prints "AtomEntry"

}

}

就得到你所要的接口参数了!

属于重点,在系统中用到注解权限时非常有用,可以精确控制权限的粒度

注意:要想使用反射去读取注解,必须将Retention的值选为Runtime Java代码import javalangannotationAnnotation;import javalangreflectMethod;//读取注解信息public class ReadAnnotationInfoTest {    public static void main(String[] args) throws Exception {        // 测试AnnotationTest类,得到此类的类对象        Class c = ClassforName(comiwtxokhtdannotationAnnotationTest);        // 获取该类所有声明的方法        Method[] methods = cgetDeclaredMethods();        // 声明注解集合        Annotation[] annotations;        // 遍历所有的方法得到各方法上面的注解信息        for (Method method : methods) {            // 获取每个方法上面所声明的所有注解信息            annotations = methodgetDeclaredAnnotations();            // 再遍历所有的注解,打印其基本信息            Systemoutprintln(methodgetName());            for (Annotation an : annotations) {                Systemoutprintln(方法名为: + methodgetName() + 其上面的注解为: + anannotationType()getSimpleName());                Method[] meths = anannotationType()getDeclaredMethods();                // 遍历每个注解的所有变量                for (Method meth : meths) {                    Systemoutprintln(注解的变量名为: + methgetName());                }            }        }    }}

以上就是关于java 什么情况下是用反射的获取方法全部的内容,包括:java 什么情况下是用反射的获取方法、如何利用java反射,获取属性接口的具体类、Java 注解的读取注解信息的方法等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9739357.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存