zoukankan      html  css  js  c++  java
  • 利用反射机制编写校验参数(对象及属性)为空的情况

    
    
    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!");}}}
    }
    }}

  • 相关阅读:
    Kubernetes 1.5部署sonarqube
    Kubernetes 1.5集成heapster
    Kubernetes 1.5 配置dashboard
    SQL SERVER中的逻辑读取,物理读取,以及预读的理解
    JS控制显示/隐藏二级菜单
    Css下拉菜单设置
    div包裹页面后多余部分没有显示,也没滚动条 overflow 属性设置
    Sql Ado.net 学习笔记之连接字符串
    Winform异步解决窗体耗时操作(Action专门用于无返回值,Func专门用于有返回值)
    SQL中的字母的大小写转换
  • 原文地址:https://www.cnblogs.com/zhaoran8775/p/6972298.html
Copyright © 2011-2022 走看看