zoukankan      html  css  js  c++  java
  • 反射找到成员

    package com.yd.wmsc.util;
    
    import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.Field;
    import java.util.ArrayList;
    import java.util.List;
    
    public class ReflectTest {
        public static List<String> getPrefixList(Class Clazz, String prefix) {
            List<String> list = new ArrayList<String>();
            try {
                // 或得bean类
                BeanInfo beninfo = Introspector.getBeanInfo(Clazz);
                Field[] fields = Clazz.getDeclaredFields();
                for (Field field : fields) {
                    System.out.println(field.getName());
                }
    
                System.out.println("======================================");
                // 获得所有的属性描述
                PropertyDescriptor[] propertydescriptors = beninfo.getPropertyDescriptors();
                for (PropertyDescriptor pd : propertydescriptors) {
                    System.out.println(pd.getName());
                    if (pd.getName().startsWith(prefix)) {
                        list.add(pd.getName());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }
    
        public static void main(String[] args) {
            ReflectTest.getPrefixList(ContentWordBean.class, "TX_TYPE_");
        }
    }
    package com.yd.wmsc.util;
    
    import java.util.List;
    
    
    public class ContentWordBean {
    
        //题目类型
        private String itemType;
        //序号
        private String serial;
        //题目内容
        private String title;
        //答案
        private List<String> answerList;
        //标准答案
        private String lastAnswer;
        //答案解析
        private String analysis;
        //难度系数
        private String koc;
        //分数
        private String score;
        //章名称
        private String chapterName;
        //节名称
        private String sectionName;
        //知识点
        private String knowledge;
        //图片
            public String getKnowledge() {
            return knowledge;
        }
        /*public void setKnowledge(String knowledge) {
            this.knowledge = knowledge;
        }*/
        /*public String getItemType() {
            return itemType;
        }
        public void setItemType(String itemType) {
            this.itemType = itemType;
        }
        public String getSerial() {
            return serial;
        }
        public void setSerial(String serial) {
            this.serial = serial;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public List<String> getAnswerList() {
            return answerList;
        }
        public void setAnswerList(List<String> answerList) {
            this.answerList = answerList;
        }
        public String getLastAnswer() {
            return lastAnswer;
        }
        public void setLastAnswer(String lastAnswer) {
            this.lastAnswer = lastAnswer;
        }
        public String getAnalysis() {
            return analysis;
        }
        public void setAnalysis(String analysis) {
            this.analysis = analysis;
        }
        public String getKoc() {
            return koc;
        }
        public void setKoc(String koc) {
            this.koc = koc;
        }
        public String getScore() {
            return score;
        }
        public void setScore(String score) {
            this.score = score;
        }
        public String getChapterName() {
            return chapterName;
        }
        public void setChapterName(String chapterName) {
            this.chapterName = chapterName;
        }
        public String getSectionName() {
            return sectionName;
        }
        public void setSectionName(String sectionName) {
            this.sectionName = sectionName;
        }
        */
    }
    package com.yd.wmsc.util;
    
    import java.beans.BeanInfo;
    import java.beans.IntrospectionException;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.List;
    import java.util.Properties;
    
    public class TestReflect {
        public static void main(String[] args) throws NoSuchFieldException{
            ContentWordBean content = new ContentWordBean();
            //topicbean.setChapter_id("123");
            List<String> fields=new ArrayList<String>();
            //fields.add("topic_id");
            //fields.add("node_id");
            getInsertSql(ContentWordBean.class,fields,"e_topic","");
            getSql(ContentWordBean.class,fields);
        }
        private static void getSql(Class className,List<String> suffixs) {
            try {
                //或得bean类
                BeanInfo beninfo = Introspector.getBeanInfo(className);
                //获得所有的属性描述
                PropertyDescriptor [] propertydescriptors = beninfo.getPropertyDescriptors();
                for(PropertyDescriptor pd:propertydescriptors){
                    //获得读写方法
                    System.out.println(pd.getName());
                    System.out.println(pd.getReadMethod().getName());//
                    System.out.println(pd.getWriteMethod().getName());//
                    
                }
            } catch (IntrospectionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }    
        }
        /**通常需要将一个bean对象通过get方法插入到表中,本方法可以动态的生成sql语句
         * 将对象的sql语句生成
         * suffixs长度为空,则对所有的field进行插入
         * table为插入的表名
         * */
        public static String getInsertSql(Class className,List<String> suffixs,String table,String beanName) throws NoSuchFieldException{
            if("".equals(table)){
                System.out.println("表名为空");
                return null;                    
            }
            String sqlparam = "";
            String sql ="insert into "+table+"(sqlparam) values(";
            String bean = beanName;
            if("".equals(bean)){
                //获得类名并且将第一个字母转为小写
                bean = className.getSimpleName();;
                bean = bean.substring(0, 1).toLowerCase()+bean.substring(1);
            }
            //获得这个类的所有方法
            Method[] methods = className.getMethods();
            //是否取所有的fields
            if(suffixs.size() == 0){
                //获得私有属性
                Field[] fields = className.getDeclaredFields();
                for(Field field:fields){
                    suffixs.add(field.getName());
                }
                
                //获得共有属性
                fields = className.getFields();
                for(Field field:fields){
                    suffixs.add(field.getName());
                }
            }
            System.out.println(suffixs);
            for(String suffix:suffixs)
            {
                for(Method method:methods){
                    //判断是否由get方法
                    if(method.getName().toLowerCase().equals("get"+suffix)){
                        try {
                            //Field field = className.getDeclaredField(suffix);
                            if (method.getReturnType() == java.lang.String.class){
                                sqlparam += suffix+",";
                                sql +="'"+"+bean +"."+method.getName()+"()+"',";
                            }else
                            if (method.getReturnType() == int.class)
                            {
                                sqlparam += suffix+",";
                                sql +="'+"+bean +"."+method.getName()+"()+',";
                            }
                                
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        }
                    }
                }        
            }
            sql = sql.replace("(sqlparam)", "("+sqlparam.substring(0, sqlparam.length()-1)+")");
            sql = """+sql.substring(0, sql.length()-1)+");"";
            System.out.println(sql);
            return sql;
        }
    }
    Clazz.getDeclaredFields 找到本类所有的成员
    Clazz.getFields 找到本类及父类公有的成员
    Introspector.getBeanInfo(clazz);
    beninfo.getPropertyDescriptors()找到本类及父类所有的成员,但成员必须至少有get或set方法,并多一个class成员

    Introspector.getBeanInfo(clazz, clazz.getSuperclass()); 只找到本类所有的成员,但成员必须至少有get或set方法
     
    import java.util.List;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.reflect.FieldUtils;
    import org.springframework.http.HttpStatus;
    import org.springframework.web.server.ResponseStatusException;
    
    @Slf4j
    public class FieldsValidator {
    
      private FieldsValidator() {}
    
      public static void validateFields(Object object, List<String> fieldNames) {
    
        fieldNames.stream()
            .filter(fieldName -> fieldIsNotNull(object, fieldName))
            .findAny()
            .orElseThrow(
                () ->
                    new ResponseStatusException(HttpStatus.BAD_REQUEST, fieldNames + " are all null"));
      }
    
      public static boolean fieldIsNotNull(Object object, String fieldName) {
        try {
          Object o = FieldUtils.readField(object, fieldName, true);
          return o == null ? false : true;
        } catch (IllegalAccessException e) {
          log.error("IllegalAccessException occurred", e);
          return false;
        }
      }
    }
  • 相关阅读:
    lintcode:previous permutation上一个排列
    lintcode : 二叉树的序列化和反序列化
    lintcode : find peak element 寻找峰值
    lintcode 中等题:搜索旋转排序数组II
    lintcode :搜索旋转排序数组
    lintcode: search for a range 搜索区间
    lintcode:最大子数组差
    lintcode:最大子数组II
    lintcode :最大子数组
    lintcode : 平衡二叉树
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/6610818.html
Copyright © 2011-2022 走看看