• 利用反射机制编写校验参数(对象及属性)为空的情况


    
    
    package com.ry.check;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class MyCheck {
        public static void main(String[] args) throws IllegalAccessException,
                IllegalArgumentException, InvocationTargetException {
            MyCheck check = new MyCheck();
            Student student = new Student();
            student.setName("zzzz");
            student.setAddress("sss");
            student.setIdno("5664");
    //        student.setPhone("sss");
            check.test1(student);
    
        }
    
        public void test(Student student) throws IllegalAccessException,
                IllegalArgumentException, InvocationTargetException {
            CheckParamUtil<Student> checkParamUtil = new CheckParamUtil<Student>();
            checkParamUtil.checkParam(student);
            System.out.println("student:" + student);
        }
    
        public void test1(Student student) throws IllegalAccessException,
                IllegalArgumentException, InvocationTargetException {
            CheckParamUtil<Student> checkParamUtil = new CheckParamUtil<Student>();
            checkParamUtil.checkParam(student, "name", "address", "idno","phone");
            System.out.println("student:" + student);
        }
    
    }
    
    class Student {
        private String name;
        private int age;
        private String address;
        private String idno;
        private String phone;
    
        public Student() {
        }
    
        public Student(String name, int age, String address, String idno,
                String phone) {
            super();
            this.name = name;
            this.age = age;
            this.address = address;
            this.idno = idno;
            this.phone = phone;
        }
    
        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 String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        public String getIdno() {
            return idno;
        }
    
        public void setIdno(String idno) {
            this.idno = idno;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    
        @Override
        public String toString() {
            return "Student [name=" + name + ", age=" + age + ", address="
                    + address + ", idno=" + idno + ", phone=" + phone + "]";
        }
    
        public void a() {
            System.out.println("haha");
        }
    }
    
    class CheckParamUtil<T> {
        /**
         * 
         * @Title:checkParam
         * @Description:(该方法用来校验对象及其属性是否为空)
         * @param t
         * @param args
         * @author
         * @throws InvocationTargetException
         * @throws IllegalArgumentException
         * @throws IllegalAccessException
         * @修改时间:2017年6月9日 下午2:18:54
         * @修改内容:创建
         */
        public void checkParam(T t, String... args) throws IllegalAccessException,
                IllegalArgumentException, InvocationTargetException {
            // 如果传入的对象为空,则直接抛出异常
            if (t == null) {
                throw new IllegalArgumentException("This object cann't be empty!");
            }
            Class<? extends Object> clazz = t.getClass();
            // 定义属性列表
            List<String> argsList = new ArrayList<String>();
            // 如果传入的属性名不为空,则将传入的属性名放入属性列表
            if (args != null && args.length > 0) {
                argsList = Arrays.asList(args);
            } else {// 如果传入的属性名为空,则将所有属性名放入属性列表
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    argsList.add(field.getName());
                }
            }
            // 获取该类自定义的方法数组
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                // 方法名
                String methodName = method.getName();
                // 获取方法对应的属性名
                String fieldName = "";
                if (methodName.length() >= 4) {
                    fieldName = methodName.substring(3, 4).toLowerCase()
                            + methodName.substring(4);
                    // 如果方法是“get方法”,并且属性列表中包含该方法对应的属性名
                    if (methodName.startsWith("get")
                            && argsList.contains(fieldName)) {
                        // 如果为null,抛出异常
                        if (method.invoke(t) == null) {
                            throw new IllegalArgumentException(fieldName
                                    + " cann't be null!");
                        }
                        // 如果该方法返回类型为String,返回结果为空字符串,抛出异常。
                        Class<?> returnType = method.getReturnType();
                        String returnTypeName = returnType.getSimpleName();
                        if (returnTypeName.equals("String")
                                && "".equals(((String)(method.invoke(t))).trim())) {
                            throw new IllegalArgumentException(fieldName
                                    + " cann't be empty String!");
                        }
                    }
                }
    
            }
    
        }
    }
    
    
    
     

    package com.ry.check;
    import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List;
    public class MyCheck {public static void main(String[] args) throws IllegalAccessException,IllegalArgumentException, InvocationTargetException {MyCheck check = new MyCheck();Student student = new Student();student.setName("zzzz");student.setAddress("sss");student.setIdno("5664");//student.setPhone("sss");check.test1(student);
    }
    public void test(Student student) throws IllegalAccessException,IllegalArgumentException, InvocationTargetException {CheckParamUtil<Student> checkParamUtil = new CheckParamUtil<Student>();checkParamUtil.checkParam(student);System.out.println("student:" + student);}
    public void test1(Student student) throws IllegalAccessException,IllegalArgumentException, InvocationTargetException {CheckParamUtil<Student> checkParamUtil = new CheckParamUtil<Student>();checkParamUtil.checkParam(student, "name", "address", "idno","phone");System.out.println("student:" + student);}
    }
    class Student {private String name;private int age;private String address;private String idno;private String phone;
    public Student() {}
    public Student(String name, int age, String address, String idno,String phone) {super();this.name = name;this.age = age;this.address = address;this.idno = idno;this.phone = phone;}
    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 String getAddress() {return address;}
    public void setAddress(String address) {this.address = address;}
    public String getIdno() {return idno;}
    public void setIdno(String idno) {this.idno = idno;}
    public String getPhone() {return phone;}
    public void setPhone(String phone) {this.phone = phone;}
    @Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + ", address="+ address + ", idno=" + idno + ", phone=" + phone + "]";}
    public void a() {System.out.println("haha");}}
    class CheckParamUtil<T> {/** *  * @Title:checkParam * @Description:(该方法用来校验对象及其属性是否为空) * @param t * @param args * @author * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException * @修改时间:2017年6月9日 下午2:18:54 * @修改内容:创建 */public void checkParam(T t, String... args) throws IllegalAccessException,IllegalArgumentException, InvocationTargetException {// 如果传入的对象为空,则直接抛出异常if (t == null) {throw new IllegalArgumentException("This object cann't be empty!");}Class<? extends Object> clazz = t.getClass();// 定义属性列表List<String> argsList = new ArrayList<String>();// 如果传入的属性名不为空,则将传入的属性名放入属性列表if (args != null && args.length > 0) {argsList = Arrays.asList(args);} else {// 如果传入的属性名为空,则将所有属性名放入属性列表Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {argsList.add(field.getName());}}// 获取该类自定义的方法数组Method[] methods = clazz.getDeclaredMethods();for (Method method : methods) {// 方法名String methodName = method.getName();// 获取方法对应的属性名String fieldName = "";if (methodName.length() >= 4) {fieldName = methodName.substring(3, 4).toLowerCase()+ methodName.substring(4);// 如果方法是“get方法”,并且属性列表中包含该方法对应的属性名if (methodName.startsWith("get")&& argsList.contains(fieldName)) {// 如果为null,抛出异常if (method.invoke(t) == null) {throw new IllegalArgumentException(fieldName+ " cann't be null!");}// 如果该方法返回类型为String,返回结果为空字符串,抛出异常。Class<?> returnType = method.getReturnType();String returnTypeName = returnType.getSimpleName();if (returnTypeName.equals("String")&& "".equals(((String)(method.invoke(t))).trim())) {throw new IllegalArgumentException(fieldName+ " cann't be empty String!");}}}
    }
    }}

  • 相关阅读:
    《RTC — RTC相关操作以及如何同步系统时间》
    《关闭服务器,再次启动服务器提示bind:address already in use》
    《海思中内存分配和优化》
    《开发板 — 查看共享内存情况》
    《通过himm读取指定引脚并保存在共享内存中》
    《开发板 — 格式化TF卡》
    《网络编程 — UDP》
    《网络编程 — 服务器中bind的ip地址是什么》
    《使用gdb中core dump》
    《 Linux套接字编程中的5个隐患 》
  • 原文地址:https://www.cnblogs.com/zhaoran8775/p/6972298.html
Copyright © 2020-2023  润新知