具有樣品類
public class SampleClass {
private String a, b, c, d, e, f;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public String getD() {
return d;
}
public void setD(String d) {
this.d = d;
}
public String getE() {
return e;
}
public void setE(String e) {
this.e = e;
}
public String getF() {
return f;
}
public void setF(String f) {
this.f = f;
}
}
你可以在Java豆信息使用java.beans.Introspector
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
public class IntrospectorTest {
@Test
public void test() throws IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
SampleClass sampleClass = new SampleClass();
sampleClass.setA("value for a");
sampleClass.setB("value for b");
sampleClass.setC("value for c");
sampleClass.setD("value for d");
sampleClass.setE("value for e");
sampleClass.setF("value for f");
int withValue = 0;
PropertyDescriptor[] descriptors = Introspector.getBeanInfo(SampleClass.class, Object.class).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : descriptors) {
Object value = new PropertyDescriptor(propertyDescriptor.getName(), SampleClass.class).getReadMethod().invoke(sampleClass);
if (value!=null) {
withValue++;
System.out.println(propertyDescriptor.getName() + ": " + value);
}
}
if (descriptors.length == withValue || withValue == 0) {
System.out.println("valid");
}else{
System.err.println("Invalid!!");
}
}
}
和瞧!在這條線
收費atention
Introspector.getBeanInfo(SampleClass.class, Object.class).getPropertyDescriptors();
,如果你與你的類調用getBeanInfo
方法唯一參數Introspector
將返回所有屬性描述中的類層次結構,這樣你就可以調用該方法一個可選的停止類,其中Introspector
停止讀取屬性描述符。
希望這會有所幫助。
查看java.util.Map – nablex 2014-10-29 15:19:41
如果你想堅持常規的java變量,你必須使用反射:http://docs.oracle.com/javase/tutorial/reflect/ – 2014-10-29 15:26:26