java/ch/wlkl/wsh/Get.java

package ch.wlkl.wsh;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//???import com.sun.org.apache.xerces.internal.impl.xpath.regex.RegularExpression;

public class Get extends Top {
    public static Pattern pa = Pattern.compile("[^.${}]+");

    public static Object get(Object obj, String key) {
        try {
            Method m = obj.getClass().getMethod("get", String.class);
            return m.invoke(obj, new Object[] {key}); 
        } catch (Exception eG) {
            try {
                Method m = obj.getClass().getMethod(key);
                return m.invoke(obj, (Object[]) null); 
            } catch (Exception em) {
                try {
                    Field f = obj.getClass().getField(key);
                    return f.get(obj);
                } catch (Exception ef) {
                    sFail("no get/method/field " + key + " for class " + obj.getClass() + " instance " + obj
                            + "\nget " + eG + "\nmethod: " + em + "\nfield: " + ef);
                }
            }
        }
        return null;
    }

    public static boolean hasKey(Object obj, String key) {
        try {
            get(obj, key);
            return true;
        } catch (Throwable e) {
            return false;
        }
    }
    
    public static Object via(Object obj, String key) {
        if (key == null || key.equals(""))
            sFail("empty key for via(" + obj + ", " + key + ")");
        return via(obj, pa.matcher(key));
    }

    public static Object via(Object obj, Matcher key) {
        if (! key.lookingAt()) 
            sFail("bad key at pos " + key.regionStart() + " for via(" + obj + ", " + key.region(0, key.regionEnd()) + ")");
        sFail("destroyied code!!!");
        return null;
        
    //    return via(obj, pa.matcher(key));
    }
/* ???     what was this code for ?????????????????????
re.m int c;
        int e = -1;
        while ((e = key.indexOf('.', c = e+1)) >= 0)
            g = make(g.get(key.substring(c, e)), null);
        return (C) g.get(key.substring(c));
    }
*/
}