Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Obtaining the value of a public static field by reflexion

// Obtaining the value of a static public constant of a class, here Boolean for example
        Object returnedObj = null;
        try {
            Class clazz = Class.forName("java.lang.Boolean");
            returnedObj = clazz.getField("TRUE").get(clazz);
            assert java.lang.Boolean.TRUE == returnedObj : "wrong returned object";
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return returnedObj;

Constants in python

From Alex's recipe.
# Put in const.py...:
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):
            raise self.ConstError, "Can't rebind const(%s)"%name
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()

that's all -- now any client-code can
import const
const.magic = 23     # bind an attribute ONCE
const.magic = 88     # raises const.ConstError if re-bind

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS