2014-10-29 64 views
0
String a = "1"; 
String b; 
... 
String n = "100"; 

如何檢查是否沒有設置任何屬性或全部屬性?如何檢測是否只設置了部分屬性?

如果設置了所有屬性,我想獲得「有效」,如果設置了所有屬性,也要設置「有效」。但如果只是部分設置,則爲「無效」。

這怎麼解決?當然,我可以寫無盡的布爾之類的語句

(a != null && b != null & .. & n != null) || (a == null && b == null & .. & n == null)

但是,必須有一個更好的辦法。

+0

查看java.util.Map – nablex 2014-10-29 15:19:41

+0

如果你想堅持常規的java變量,你必須使用反射:http://docs.oracle.com/javase/tutorial/reflect/ – 2014-10-29 15:26:26

回答

1

具有樣品類

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停止讀取屬性描述符。

希望這會有所幫助。

0

您可以使用映射然後迭代它來檢查是否有任何值爲空並相應地設置狀態。

您也可以嘗試使用此:Collections.frequency(map.values(),NULL)== map.size()

相關問題