java访问私有属性

一直以来,Java初学者甚至有多年开发经验的人,都认为在该类的外部,是不能访问其私有属性的。其实不然,下面是我写的一个很小的例子来证明这一点:
package com.active.demo;
import java.lang.reflect.Field;
public class PrintUtil {
/**
* this method can print all the not-null value of fields that the given object has.
* @param obj: any object that you want to print
*/
public static void print(Object obj) {
try {
//get the object's class
Class clazz = obj.getClass();
//get all the fields that this object has
Field[] fields = clazz.getDeclaredFields();
String fieldName = "";
Object fieldValue;
if (fields != null && fields.length > 0) {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
//if and only if we set accessible to true,
//we can access all fields, no matter which scope it is
field.setAccessible(true);
fieldValue = field.get(obj);
if (fieldValue != null) {
fieldName = field.getName();
System.out.println(fieldName + ":\t\t" + fieldValue);
}
}
}
} catch (Exception e) {
throw new RuntimeException("can not print ["
+ obj.getClass().getName() + "] field");
}
}
//this is for test
public static void main(String[] args) {
TestPrintBean tpb = new TestPrintBean();
tpb.setPriveteField("this is a value of private field");
tpb.setProtectedField("this is a value of protected field");
tpb.setPublicField("this is a value of public field");
print(tpb);
}
-----------------------------------------------------
This is a bean object just for testing
-----------------------------------------------------
package com.active.demo;
public class TestPrintBean{
private String priveteField;
private String priveteField2;
protected String protectedField;
public String publicField;
/**
* @return the priveteField
*/
public String getPriveteField() {
return priveteField;
}
/**
* @param priveteField the priveteField to set
*/

public void setPriveteField(String priveteField) {
this.priveteField = priveteField;
}
/**
* @return the priveteField2
*/
public String getPriveteField2() {
return priveteField2;
}
/**
* @param priveteField2 the priveteField2 to set
*/
public void setPriveteField2(String priveteField2) {
this.priveteField2 = priveteField2;
}
/**
* @return the protectedField
*/
public String getProtectedField() {
return protectedField;
}
/**
* @param protectedField the protectedField to set
*/
public void setProtectedField(String protectedField) {
this.protectedField = protectedField;
}
/**
* @return the publicField
*/

public String getPublicField() {
return publicField;
}
/**
* @param publicField the publicField to set
*/

public void setPublicField(String publicField) {
this.publicField = publicField;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值