• Treflection04_面试题


    1、

    package reflectionZ;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    public class Treflection04
    {
        // 第17讲
        
        public static void main(String[] args) throws Exception
        {
            Test2 test2 = new Test2();
            //int iRtn = Sum01(test2);
            int iRtn = Sum02(test2);
            System.out.println("iRtn : "+iRtn);
        }
        
        public static int Sum01(Test2 _test2) throws Exception
        {
            int iRst = 0;
            Class<?> clazz1 = Class.forName("reflectionZ.Test2");
            Field[] fields = clazz1.getDeclaredFields();
            for (int i=0; i<fields.length; i++)
            {
                Field field = fields[i];
                System.out.println("field.getGenericType() : "+field.getGenericType());
                //if (int.class == field.getType()) // 方法1
                if (field.getGenericType().toString().equalsIgnoreCase("int")) // 方法2
                {
                    field.setAccessible(true);
                    int j = field.getInt(_test2);
                    iRst += j;
                }
            }
            
            return iRst;
        }
        
        public static int Sum02(Test2 _test2) throws Exception
        {
            int iRst = 0;
            Class<?> clazz1 = Class.forName("reflectionZ.Test2");
            Method[] methods = clazz1.getMethods();
            for (int i=0; i<methods.length; i++)
            {
                Method method = methods[i];
                if (method.getName().startsWith("get") && (! method.getName().equalsIgnoreCase("getClass"))) // 排除掉 getClass()
                {
                    // 函数 有返回值,处理方式
                    //int j = (int)method.invoke(_test2); // ZC: 这种处理方式 ==> 行不通
                    Integer j = (Integer)method.invoke(_test2);
                    iRst += j;
                }
            }
            
            return iRst;
        }
    }
    
    class Test2
    {
        public static final Long serverUID = 1L;
        
        private int FiIdx1 = 10;
        private int FiIdx2 = 20;
        private int FiIdx3 = 30;
        private int FiIdx4 = 40;
        private int FiIdx5 = 50;
        
        public int getFiIdx1() {
            return FiIdx1;
        }
        public int getFiIdx2() {
            return FiIdx2;
        }
        public int getFiIdx3() {
            return FiIdx3;
        }
        public int getFiIdx4() {
            return FiIdx4;
        }
        public int getFiIdx5() {
            return FiIdx5;
        }
    }

    2、

  • 相关阅读:
    iOS开发 当前时间 时间戳 转换
    iOS开发 下滑隐藏Tabbar
    iOS开发 浅见runloop
    iOS开发 检测版本更新
    IOS开发 二维码功能的实现
    级数
    算法-快速排序
    struts2.0中struts.xml配置文件详解【转】
    javascript原型【转】
    AOP各种的实现【转】
  • 原文地址:https://www.cnblogs.com/javaskill/p/5428284.html
Copyright © 2020-2023  润新知