PropertyUtil { public static String getStaticPropertyAsString(Class clazz, String field) throws NoSuchFieldException { String value = null; try { Field f = clazz.getDeclaredField(field); if (Modifier.isStatic(f.getModifiers()) && f.get(clazz) != null) { value = f.get(clazz).toString(); } } catch (SecurityException se) { throw new RuntimeException(se.getMessage(), se); } catch (IllegalArgumentException iae) { throw new RuntimeException(iae); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } return value; } private  PropertyUtil(); static String getStaticPropertyAsString(Class clazz, String field); static String getStaticPropertyAsString(String cname, String field);  }
@Test public void testStaticPropertyClassName() { try { String v = PropertyUtil.getStaticPropertyAsString( getClass().getName(), "FOO"); assertNotNull(v); assertEquals("foobar", v); } catch (NoSuchFieldException e) { fail(e.getMessage()); } catch (ClassNotFoundException cnfe) { fail(cnfe.getMessage()); } }
@Test public void testStaticProperty() { try { String v = PropertyUtil.getStaticPropertyAsString(getClass(), "FOO"); assertNotNull(v); assertEquals("foobar", v); } catch (NoSuchFieldException e) { fail(e.getMessage()); } }
@Test public void testStaticPropertyNonExistent() { try { PropertyUtil.getStaticPropertyAsString(getClass(), "BAR"); fail("BAR should've thrown exception"); } catch (NoSuchFieldException e) { assertTrue(true); } }
@Test public void testStaticPropertyNull() { try { PropertyUtil.getStaticPropertyAsString((Class) null, "FOO"); fail("Should've thrown NPE"); } catch (NullPointerException npe) { assertTrue(true); } catch (NoSuchFieldException e) { fail("should've thrown NPE"); } try { PropertyUtil.getStaticPropertyAsString(getClass(), null); fail("Should've thrown NPE"); } catch (NullPointerException npe) { assertTrue(true); } catch (NoSuchFieldException e) { fail("should've thrown NPE"); } }
@Test public void testStaticPropertyConversion() { try { String v = PropertyUtil.getStaticPropertyAsString(getClass(), "TRYME"); assertNotNull(v); assertEquals("10", v); v = PropertyUtil.getStaticPropertyAsString(getClass(), "NULL"); assertNull(v); } catch (NoSuchFieldException e) { fail("TRYME should've been found"); } }