集册 Java实例教程 通过反射获取属性

通过反射获取属性

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

452
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过反射获取属性

/*

 * Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is

 * licensed under BSD license. Use it as you wish, but keep this copyright

 * intact.

 *//**时 代      J a v a   公   众 号 - nowjava.com**/

//package com.nowjava;

import java.lang.reflect.AccessibleObject;

import java.lang.reflect.Field;

import java.util.HashMap;

import java.util.Map;


public class Main {

    public static void main(String[] argv) throws Exception {

        Object obj = "nowjava.com";

        System.out.println(getPropertiesByReflect(obj));

    }


    @SuppressWarnings("rawtypes")

    public static Map getPropertiesByReflect(Object obj) throws Exception {

        if (obj == null)

            return null;

        Field[] fields = obj.getClass().getDeclaredFields();

        if (fields == null || fields.length == 0)//来自 nowjava.com - 时代Java

            return null;

        Map<String, Object> map = new HashMap<String, Object>();

        AccessibleObject.setAccessible(fields, tru
展开阅读全文