zoukankan      html  css  js  c++  java
  • Java 反射的使用

    package com.justbon.bestsign.common.contract.client;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.List;
    public class Test {
    
        public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException {
            Class<?> cat = Class.forName("com.justbon.bestsign.common.contract.client.cat");
            cat OBJ = (com.justbon.bestsign.common.contract.client.cat) cat.newInstance();
            Field[] fields = cat.getFields();
            for (Field f : fields) {
                if (f.getName().equals("arrayListoo")) {
                    try {
                        // ======
                        List arr=new ArrayList<String>();
                        Method method01 =  arr.getClass().getMethod("add", Object.class);
                        method01.invoke(arr,"123456");
                        arr.forEach(e->{
                            System.out.println(e.toString());
                        });
                        // 这里的f.getClass()就是cat来里面的arrayListoo,但是添加会报错
                        Class<? extends Field> aClass = f.getClass();
                        Class<?> type = f.getType();
    
                        Method method = type.getMethod("add",  Object.class);
                        method.invoke(OBJ.arrayListoo, "123456");
                        OBJ.arrayListoo.forEach(e -> {
                            System.out.println("======================");
                            System.out.println(e);
                        });
    
    
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
    
                }
    
            }
        }
    }
    
    
    package com.fanshe;
    import java.util.ArrayList;
    import java.util.List;
    public class cat {
        public   List  arrayListoo=new ArrayList<String>();
        public void   getcat(){
            arrayListoo.add("1");
        }
    }
  • 相关阅读:
    2017-5-16
    2017-3-6 Develop Engineer 面试
    2017 3-4/5 两天的学习的REVIEW
    2017-3-2 C# WindowsForm 中label标签居中显示
    css图片响应式+垂直水平居中2
    flash上传在spring mvc中出现的问题2
    avalon js实现拖动图片排序
    css图片响应式+垂直水平居中1
    flash上传在spring mvc中出现的问题1
    mybatis Result Maps对结果分组3--一对多使用limit
  • 原文地址:https://www.cnblogs.com/xiaoniuniu886/p/15319774.html
Copyright © 2011-2022 走看看