zoukankan      html  css  js  c++  java
  • 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、

  • 相关阅读:
    minimsg升级扩展
    一起学习Avalonia(十三)
    @Import注解源码
    Python入门随记(3)
    NET WebApi 后端重定向指定链接
    Net Nlog 持久化到数据库
    NetCore Xunit单元测试依赖注入
    VS 调试时,提示无法启动iis服务器
    NET 反射,对可空类型动态赋值
    MSSQL 查询表结构
  • 原文地址:https://www.cnblogs.com/javaskill/p/5428284.html
Copyright © 2011-2022 走看看