`

私有成员的访问

 
阅读更多
不通过getXXX()方法获取类的私有域:

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;
}
}

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);
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics