现在的位置: 首页 > 综合 > 正文

使用反射机制动态加载配置文件

2018年04月14日 ⁄ 综合 ⁄ 共 765字 ⁄ 字号 评论关闭

1、properties文件:

name=Contacts
sourceDirectory=db/contacts
sourceClass=com.funambol.syncclient.spds.source.VCardSyncSource
type=text/x-vcard
encode=false
sync=two-way
last=1323853551062
sourceURI=card

2、设置属性

private void setProperty(SyncSource source, String key, String value) {
        String methodName = "";

        char firstLetter = key.toUpperCase().charAt(0);
        if (key.length() > 1) {
            methodName = key.substring(1);
        }

        methodName = "set" + firstLetter + methodName;

        Class sourceClass = source.getClass();

        try {
            Method m = sourceClass.getMethod(methodName, new Class[] { String.class });//第二个参数指定参数类型
            m.invoke(source, new String[] {value});//第二个参数传入方法的参数值
        } catch (Exception e) {
            String msg = "Property "                 +
                          key                        +
                          " not set to "             +
                          value                      +
                          ". Method "                +
                          methodName                 +
                          "(String s) not found in " +
                          sourceClass.getName()      ;

            if (logger.isLoggable(Logger.DEBUG)) {
                logger.debug(msg);
            }

        }
    }

抱歉!评论已关闭.