Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 273|回复: 0

[Java反射学习]通过注释和反射读写属性文件

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-30 23:58:00 | 显示全部楼层 |阅读模式
    // PropertiesUtils.java
        import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.Properties;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
        /**
    * 读写属性文件
    * @date 2009-12-7 下午09:15:03
    */
    public class PropertiesUtils {
         private String file_path = null;
         private Properties properties = null;
         /**
          * 构造函数
          * @param file_path
          */
         public PropertiesUtils(String file_path){
             this.file_path = file_path;
             File file = new File(file_path);
             FileInputStream in = null;
             try {
                 String dir = file.getParent();
                 if(needMkdirs(dir)){         // 需要创建目录时创建目录
                     new File(dir).mkdirs();
                 }
                 if(!file.exists()){          // 文件不存在时创建文件
                     file.createNewFile();
                 }
                 in = new FileInputStream(file_path);
                 properties = new Properties();
                 properties.load(in);
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         /**
          * 根据 key 返回其 value
          * @param key
          * @return
          */
         public String getValue(String key){
             if(properties == null){
                 return null;
             }
             return properties.getProperty(key);
         }
         /**
          * 根据属性文件返回一个 databean
          * 该 databean 必须提供一个默认的 构造函数
          * @param cls
          * @param obj
          * @return
          */
         public Object getBean(Class cls){
             if(properties == null){
                 return null;
             }
             Object obj = null;
             try {
                 // 实例化一个对象
                 Constructor cons = cls.getDeclaredConstructor(); // 默认构造函数
                 obj = cons.newInstance();
                 // 返回所有声明的域 ,包括 private 的域
                 Field[] fds = cls.getDeclaredFields();
                 // 构造 set 方法
                 String fname = "";
                 String setMethod = "";
                 for(int i=0; i < fds.length; i++){
                     fname = fds.getName();                 // 取出字段名称
                     setMethod = "set"                         // 构造 set 方法
                         + Character.toUpperCase(fname.charAt(0))
                         + fname.substring(1);
                     PropertyField f = fds.getAnnotation(PropertyField.class);
                     String key = f.key();                     // 取出当前字段所对应注解值key
                     String val = getValue(key);               // 取出对象的属性值
                     // 创建 Method
                     Method m = cls.getMethod(setMethod, String.class);
                     // 调用 Method 方法
                     m.invoke(obj, val);
                 }
             } catch (SecurityException e) {
                 e.printStackTrace();
             } catch (Exception e) {
                 e.printStackTrace();
             }
             return obj;
         }
         /**
          * 将 databean 保存到属性文件中
          * @param obj
          */
         public void saveBean(Object obj){
             if(properties == null){
                 return;
             }
             Class<? extends Object> cls = obj.getClass();
             try {
                 // 返回所有声明的域 ,包括 private 的域
                 Field[] fds = cls.getDeclaredFields();
                 // 构造 get 方法
                 String fname = "";
                 String getMethod = "";
                 for(int i=0; i < fds.length; i++){
                     fname = fds.getName();                 // 取出字段名称
                     getMethod = "get"                         // 构造 get 方法
                         + Character.toUpperCase(fname.charAt(0))
                         + fname.substring(1);
                     PropertyField f = fds.getAnnotation(PropertyField.class);
                     String key = f.key();                     // 取出当前字段所对应注解值key
                     // 创建 Method
                     Method m = cls.getMethod(getMethod);
                     // 调用 Method 方法
                     String val = (String)m.invoke(obj);
                     setValue(key, val);
                 }
             } catch (SecurityException e) {
                 e.printStackTrace();
             } catch (Exception e) {
                 e.printStackTrace();
             }
             // 将属性文件保存到文件
             save();
         }
         /**
          * 设置属性值
          * @param key
          * @param value
          */
         public void setValue(String key,String value){
             if(properties == null){
                 return;
             }
             properties.setProperty(key, value);
         }
         /**
          * 添加属性值
          * @param key
          * @param value
          */
         public void addValue(String key,String value){
             if(properties == null){
                 return;
             }
             properties.put(key, value);
         }
         /**
          * 根据 key 移除属性
          * @param key
          */
         public void removeValue(String key){
             if(properties == null){
                 return;
             }
             properties.remove(key);
         }
         /**
          * 保存当前属性文件
          */
         public void save(){
             if(properties == null){
                 return;
             }
             FileOutputStream out = null;
             try {
                 out = new FileOutputStream(file_path);
                 properties.store(out, "##");
             } catch (IOException e) {
                 e.printStackTrace();
             } finally{
                 if(out != null){
                     try {
                         out.flush();
                         out.close();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                 }
             }
         }
         /**
          * 是否需要创建目录
          * @param dir
          * @return
          */
         private boolean needMkdirs(String dir){
             File d = new File(dir);
             String path = d.getAbsolutePath();
             // 判断是否是根目录
             Pattern pattern = Pattern.compile("^[A-Za-z]:(\\|/)$");
             Matcher matcher = pattern.matcher(path);
             boolean res = matcher.matches();
             if(d.exists() || res){         // 目录已存在 或者 是磁盘根目录时不需创建目录
                 return false;
             }
             return true;
         }

    //测试
         public static void main(String args[]){
          PropertiesUtils pu=new PropertiesUtils("./webcom.properties");
          Object ob=pu.getBean(WebComponent.class);
          System.out.println(((WebComponent)ob).getDefaultImages());
              WebComponent we=new WebComponent();
          we.setDefaultImages("images/login1.gif");
          we.setDefaultJs("js/index1.jsp");
          we.setDefaultCss("css/index1.css");
           pu.saveBean(we);
    }
      
       
    }
        // PropertyField.java
        import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    /**
    * 注解
    * @date 2009-12-9 上午10:35:43
    */
    @Target(ElementType.FIELD)            // 域声明 : 表示注解用在什么地方
    @Retention(RetentionPolicy.RUNTIME)   // 在 JVM 运行期也保留注解 : 表示注解的级别
    @Documented                           // 将此注解包含在 javadoc 中
    @Inherited                            // 允许子类继承父类中的注解
    public @interface PropertyField{
         String key();
         String description() default "";
    }
        // WebComponent.java
        /**
    * databean
    * @date 2009-12-9 上午10:45:47
    */
    public class WebComponent {
         @PropertyField(key="skin.default.images")
         private String defaultImages;     
         
         @PropertyField(key="skin.default.js")
         private String defaultJs;
         
         @PropertyField(key="skin.default.css")
         private String defaultCss;
            public String getDefaultImages() {
             return defaultImages;
         }
            public void setDefaultImages(String defaultImages) {
             this.defaultImages = defaultImages;
         }
            public String getDefaultJs() {
             return defaultJs;
         }
            public void setDefaultJs(String defaultJs) {
             this.defaultJs = defaultJs;
         }
            public String getDefaultCss() {
             return defaultCss;
         }
            public void setDefaultCss(String defaultCss) {
             this.defaultCss = defaultCss;
         }
    }
       

       
         
         
          
          

            
          

            
          
         
       

      


    源码下载:http://file.javaxxz.com/2014/10/30/235759984.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-6 02:30 , Processed in 0.489709 second(s), 48 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表