將類中所有屬性和值新增到Map中
阿新 • • 發佈:2019-01-28
public class FunSwitch{ public int clientFile=0; public String fileMonitor="wangzhiming"; public Map<String,Object> toMap(){ Map<String,Object> map= new HashMap<>(); for(Field field : FunSwitch.class.getFields()){ try{ map.put(field.getName(),field.get(this)); }catch(Exception e){ } } return map; } }
getFields()與getDeclaredFields()區別:
getFields()只能訪問類中宣告為公有的欄位,私有的欄位它無法訪問,能訪問從其它類繼承來的公有方法.
getDeclaredFields()能訪問類中所有的欄位,與public,private,protect無關,不能訪問從其它類繼承來的方法
getMethods()與getDeclaredMethods()區別:
getMethods()只能訪問類中宣告為公有的方法,私有的方法它無法訪問,能訪問從其它類繼承來的公有方法.
getDeclaredMethods()能訪問類中所有的欄位,與public,private,protect無關,不能訪問從其它類繼承來的方法
getConstructors()與getDeclaredConstructors()區別:
getConstructors()只能訪問類中宣告為public的建構函式.
getDeclaredConstructors()能訪問類中所有的建構函式,與public,private,protect無關