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、

原文地址:https://www.cnblogs.com/javaskill/p/5428284.html