2014-10-29 33 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()

相关问题