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");
        }
    }
  • 相关阅读:
    C99新增内容之复合文字(compound literal)
    直接编译caffe出现的两个问题
    安装cuda8.0中所遇到的问题-解决办法
    windows环境Caffe安装配置步骤(无GPU)及mnist训练
    leetcodeTop100好题
    只不过是从头再来,读java源码
    文章收藏
    java代码优化技巧
    xshell
    MVC框架笔记
  • 原文地址:https://www.cnblogs.com/xiaoniuniu886/p/15319774.html
Copyright © 2011-2022 走看看