• JAVA 反射应用:properties2Object


    MixAll.java

    import java.lang.reflect.Method;
    import java.util.Properties;
    
    public class MixAll {
    
        /**
         * 将Properties中的值写入Object
         */
        public static void properties2Object(final Properties p, final Object object) {
            Method[] methods = object.getClass().getMethods();
            for (Method method : methods) {
                String mn = method.getName();
                if (mn.startsWith("set")) {
                    try {
                        String tmp = mn.substring(4);
                        String first = mn.substring(3, 4);
    
                        String key = first.toLowerCase() + tmp;
                        String property = p.getProperty(key);
                        if (property != null) {
                            Class<?>[] pt = method.getParameterTypes();
                            if (pt != null && pt.length > 0) {
                                String cn = pt[0].getSimpleName();
                                Object arg = null;
                                if (cn.equals("int")) {
                                    arg = Integer.parseInt(property);
                                } else if (cn.equals("long")) {
                                    arg = Long.parseLong(property);
                                } else if (cn.equals("double")) {
                                    arg = Double.parseDouble(property);
                                } else if (cn.equals("boolean")) {
                                    arg = Boolean.parseBoolean(property);
                                } else if (cn.equals("String")) {
                                    arg = property;
                                } else {
                                    continue;
                                }
                                method.invoke(object, new Object[] { arg });
                            }
                        }
                    } catch (Throwable e) {
                    }
                }
            }
        }
    
    }

    PersonConfig.java

    public class PersonConfig {
    
        private String name;
        private int age;
        private double saving;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public double getSaving() {
            return saving;
        }
    
        public void setSaving(double saving) {
            this.saving = saving;
        }
    
        @Override
        public String toString() {
            return "PersonConfig [name=" + name + ", age=" + age + ", saving="
                    + saving + "]";
        }
    }

    TestCommandline.java

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    import org.apache.commons.cli.CommandLine;
    import org.apache.commons.cli.CommandLineParser;
    import org.apache.commons.cli.DefaultParser;
    import org.apache.commons.cli.Option;
    import org.apache.commons.cli.Options;
    import org.apache.commons.cli.ParseException;
    
    public class TestCommandline {
        public static void main(String[] args) throws ParseException, IOException {
            Options options = new Options();
            Option opt = new Option("c", "config", true, "config file path");
            opt.setRequired(true);
            options.addOption(opt);
    
            CommandLineParser parser = new DefaultParser();
            CommandLine commandLine = parser.parse(options, args);
    
            String optNmae = "c";
            if (commandLine.hasOption(optNmae)) {
                File file = new File(commandLine.getOptionValue(optNmae));
    
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                Properties properties = new Properties();
                properties.load(in);
    
                PersonConfig personConfig = new PersonConfig();
                System.out.println(personConfig); //
                MixAll.properties2Object(properties, personConfig);
                System.out.println(personConfig); //
    
                System.out.println("load config properties file OK, " + file);
                in.close();
            }
        }
    }

    E:configperson.properties

    name=Zno
    age=18
    saving=200.0

    执行参数:

    -c E:/config/person.properties

    运行结果:

    PersonConfig [name=null, age=0, saving=0.0]
    PersonConfig [name=Zno, age=18, saving=200.0]
    load config properties file OK, E:configperson.properties

    动态修改属性

         import org.apache.commons.beanutils.BeanUtils;
    
            public void clean() {
                Field[] fields = this.getClass().getDeclaredFields();
                for (Field field : fields) {
                    try {
                        String name = field.getName();
                        String property = BeanUtils.getProperty(this, name);
                        if ("未知".equals(property)) {
                            BeanUtils.setProperty(this, name, null);
                        }
                    } catch (Exception e) {
                    }
                }
            }

    清洗更新数据,提高更新效率,避免无修改却被更新

        public static <T> void clean4update(T dataFromDb, T data4update, String ... ignores) {
            List<String> ignoreList = null;
            if(ignores != null) {
                ignoreList = Arrays.asList(ignores);
            }
            Class<? extends Object> clazz = dataFromDb.getClass();
            Set<String> fieldSet = new HashSet<String>();
            Map<String, Method> methodMap = new HashMap<String, Method>();
            Field[] fields = clazz.getDeclaredFields();
            Object[] args = new Object[] {};
            Object[] args2 = new Object[] { null };
            for (Field field : fields) {
                String name = field.getName();
                fieldSet.add(name);
            }
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                String mn = method.getName();
                if (mn.startsWith("get") || mn.startsWith("set")) {
                    String tmp = mn.substring(4);
                    String first = mn.substring(3, 4);
                    String key = first.toLowerCase() + tmp;
                    if(ignoreList.contains(key)) {
                        continue;
                    }
                    if (!fieldSet.contains(key)) {
                        continue;
                    }
                    methodMap.put(key + (mn.startsWith("get") ? ":g" : ":s"), method);
                }
            }
    
            Set<Entry<String, Method>> entrySet = methodMap.entrySet();
            for (Entry<String, Method> entry : entrySet) {
                String key = entry.getKey();
                Method method = entry.getValue();
                if (key.endsWith(":s")) {
                    continue;
                }
                try {
                    Object invoke = method.invoke(dataFromDb, args);
                    if (invoke == null) {
                        continue;
                    }
                    boolean isSame = invoke.equals(method.invoke(data4update, args));
                    if (isSame) {
                        methodMap.get(key.replace(":g", ":s")).invoke(data4update, args2);
                    }//TODO 可以设置一个返回值,除了忽略的字段,如果所有getter对应的值都相同,则返回true,有一处不同即可设置为false 
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }

    测试:

        @Test
        public void testclean4update() {
            Foo dataFromDb = new Foo();
            Date date = new Date();
            
            dataFromDb.setGmtCreate(date);
            dataFromDb.setGmtModified(date);
            dataFromDb.setPageName("啊啊啊啊");
            dataFromDb.setPagePerms("/aaaa,/bbbb");
            dataFromDb.setPageType(1);
            dataFromDb.setPageUri("/sdfsd/sdfsdf");
            dataFromDb.setRemarks("lljkjkljkjl");
            dataFromDb.setS01Id(1L);
            dataFromDb.setS02Id(2L);
            Foo data4update = new Foo();
            data4update.setGmtCreate(date);
            data4update.setGmtModified(DateUtils.delaySec(date, 2));
            data4update.setPageName("啊啊啊啊");
            data4update.setPagePerms("/aaaa,/bbbb1");
            data4update.setPageType(2);
            data4update.setPageUri("/sdfsd/sdfsdf");
            data4update.setRemarks("lljkjkljkjl");
            data4update.setS01Id(1L);
            data4update.setS02Id(2L);
            SqlUtils.clean4update(dataFromDb, data4update, "s02Id");
            System.out.println(JSONObject.toJSONString(data4update));;
        }
        public static class Foo {
            /** 自增主键 */
            private Long s02Id;
    
            /** 子系统主键,即外键 */
            private Long s01Id;
    
            /** 修改时间 */
            private Date gmtModified;
    
            /** 创建时间 */
            private Date gmtCreate;
    
            /** 页面名称 */
            private String pageName;
    
            /** 页面uri,该页面前端访问地址 */
            private String pageUri;
    
            /** 页面权限列表,英文逗号分隔/aaa,/bbb (可以为空) */
            private String pagePerms;
    
            /** 页面类型,1 需绑定到菜单,2游离页面 */
            private Integer pageType;
    
            /** 备注 */
            private String remarks;
    
            public Long getS02Id() {
                return s02Id;
            }
    
            public void setS02Id(Long s02Id) {
                this.s02Id = s02Id;
            }
    
            public Long getS01Id() {
                return s01Id;
            }
    
            public void setS01Id(Long s01Id) {
                this.s01Id = s01Id;
            }
    
            public Date getGmtModified() {
                return gmtModified;
            }
    
            public void setGmtModified(Date gmtModified) {
                this.gmtModified = gmtModified;
            }
    
            public Date getGmtCreate() {
                return gmtCreate;
            }
    
            public void setGmtCreate(Date gmtCreate) {
                this.gmtCreate = gmtCreate;
            }
    
            public String getPageName() {
                return pageName;
            }
    
            public void setPageName(String pageName) {
                this.pageName = pageName;
            }
    
            public String getPageUri() {
                return pageUri;
            }
    
            public void setPageUri(String pageUri) {
                this.pageUri = pageUri;
            }
    
            public String getPagePerms() {
                return pagePerms;
            }
    
            public void setPagePerms(String pagePerms) {
                this.pagePerms = pagePerms;
            }
    
            public Integer getPageType() {
                return pageType;
            }
    
            public void setPageType(Integer pageType) {
                this.pageType = pageType;
            }
    
            public String getRemarks() {
                return remarks;
            }
    
            public void setRemarks(String remarks) {
                this.remarks = remarks;
            }
    
            @Override
            public String toString() {
                StringBuilder sb = new StringBuilder();
                sb.append(getClass().getSimpleName());
                sb.append(" [");
                sb.append("Hash = ").append(hashCode());
                sb.append(", s02Id=").append(s02Id);
                sb.append(", s01Id=").append(s01Id);
                sb.append(", gmtModified=").append(gmtModified);
                sb.append(", gmtCreate=").append(gmtCreate);
                sb.append(", pageName=").append(pageName);
                sb.append(", pageUri=").append(pageUri);
                sb.append(", pagePerms=").append(pagePerms);
                sb.append(", pageType=").append(pageType);
                sb.append(", remarks=").append(remarks);
                sb.append("]");
                return sb.toString();
            }
        }
    Foo 类

    输出:

    {"gmtModified":1615891950943,"pagePerms":"/aaaa,/bbbb1","pageType":2,"s02Id":2}
  • 相关阅读:
    【重要】攻击动作时间段判断~使用动画time比较动画length和使用一个变量数组做延迟
    角色头上冒数字
    ApplicationListener接口的生命周期
    Blender软件基本介绍(3D建模软件)
    unity中给图片换颜色
    Unity中建立文本保存数据
    UGUI脚本添加Btn回调的方法
    碰撞体速度过快穿透的问题
    Unity中的点击,长按,划动
    在对话系统中实现打字机效果
  • 原文地址:https://www.cnblogs.com/zno2/p/4613066.html
Copyright © 2020-2023  润新知