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无关
Java反射与访问控制
本文介绍了Java反射机制中getFields(), getDeclaredFields(), getMethods(), getDeclaredMethods(), getConstructors()与getDeclaredConstructors()的区别。这些方法在访问类成员(如字段、方法和构造函数)时有不同的权限限制。
1703

被折叠的 条评论
为什么被折叠?



