栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java:反射与注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java:反射与注解

反射:框架(半成品软件)设计的灵魂


**加declared和不加declared的区别:**输出所有类型的成员变量(method) VS 输出public类型的成员变量(method)



具体的简单框架案例:

public class Writeframe {
    public static void main(String[] args) throws Exception {
        //step1:配置文件,并加载配置文件
        Properties pro=new Properties();
        //Java class.getClassLoader().getResource("")获取资源路径
        ClassLoader classLoader = Writeframe.class.getClassLoader();
        
        InputStream is = classLoader.getResourceAsStream("pro.properties");
        
        pro.load(is);//从输入字节流读取属性列表(键和元素对)。

        //step2:获取配置文件中定义的数据
        String className = pro.getProperty("className");//获取建所对应的值:类名--字符串
        String methodName = pro.getProperty("methodName");//方法名:字符串

        //step3:加载类进内存
        Class cls = Class.forName(className);//通过全类名获取class对象
        Object o = cls.newInstance();
        Method method = cls.getMethod(methodName);//感觉需要传参的情况和不需要传参的情况下有所区别(后续学习)
        method.invoke(o);//配置文件中的Person对象类的eat()方法被执行


    }
}

配置文件内容:

className=Fanshe_frame.Person
methodName=eat

API文档的生成(shift+右键:打开powershell: 输入 javadoc xxx.java):xxx.index文件

注释:本质上是接口




具体的简单框架案例:

@Pro(className = "Zhujie.Man",methodName = "show")
public class Writeframe {
    public static void main(String[] args) throws Exception {
        //step1:解析注释
        Class writeframeClass = Writeframe.class;
        //step2:获取注释对象(助手本质也是个接口!!!)
        Pro an = writeframeClass.getAnnotation(Pro.class);
        //step3:调用注释对象的抽象方法
        String cN=an.className();
        String mN = an.methodName();

        Class cls=Class.forName(cN);
        Object obj = cls.newInstance();//相当于构造方法赋值
        Method method = cls.getMethod(mN);
        method.invoke(obj);


    }
}

@Target(value={ElementType.TYPE})//这个注解只能作用于类上
@Retention(RetentionPolicy.RUNTIME)//这个注解不能少,需要被JVM读取到
public @interface Pro {
    String className();
    String methodName();
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/583073.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号