集册 Java实例教程 获取对象字段

获取对象字段

欢马劈雪     最近更新时间:2020-01-02 10:19:05

553
获取对象字段
/*
nowjava.com - 时代Java 提 供
*/


//package com.nowjava;

import java.lang.reflect.Field;


import java.util.HashMap;


public class Main {

    private static HashMap<String, Field> sFieldCache = new HashMap<String, Field>();


    public static Object getObjectField(Object object, String fieldName) {

        Object result = null;

        try {

            Field field = getField(object.getClass(), fieldName);

            result = field.get(object);/**from nowjava - 时  代  Java**/

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        } catch (IllegalArgumentException e) {

            e.printStackTrace();

        } catch (Throwable e) {

            e.printStackTrace();

        }

        return result;

    }


    private static Field getField(Class<?> clazz, String fieldName)

            throws Throwable {

        String fieldFullName = genFieldFullName(clazz, fieldName);

        if (sFieldCache.containsKey(fieldFullName))

            return sFieldCache.get(fieldFullName);

        Field field = null;

        try {

            field = clazz.getField(fieldName);

        } catch (NoSuchFieldException e) {

        }

        if (field == null) {

            try {

                field = clazz.getDeclaredField(fieldName);

                field.setAccessible(true);

            } catch (NoSuchFieldException e) {

            }

        }

        if (field == null) {

            for (clazz = clazz.getSuperclass(); clazz != Object.class; clazz = clazz

                    .getSuperclass()) {

                try {

                    field = clazz.getDeclaredField(fieldName);

                    field.setAccessible(true);

                } catch (NoSuchFieldException e) {

                }

            }

        }

        if (field == null) {

            String msg = "";

            msg = "Can't get Field from Class " + clazz.getSimpleName()

                    + ":" + fieldName;

            throw new Throwable(msg);

        }

        sFieldCache.put(fieldFullName, field);

        return field;

    }


    public static Class<?> getClass(String className) {

        Class<?> clazz = null;

        try {

            clazz = Class.forName(className);

        } catch (ClassNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return clazz;

    }


    public static Class<?> getClass(String className,

            boolean shouldInitialize, ClassLoader classLoader) {

        Class<?> clazz = null;

        
展开阅读全文