Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

In this page you can find the example usage for java.lang Class getField.

Prototype

@CallerSensitive
public Field getField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Usage

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Given a JSONObject, unmarhall it to an instance of the given class.
 *
 * @param jsonObj JSON string to unmarshall.
 * @param cls Return an instance of this class. Must be either public class
 *            or private static class. Inner class will not work.
 * @param <T> Same type as cls.//ww w .ja v a2 s  .c  o m
 * @return An instance of class given by cls.
 * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
 */
public static <T> T JSONToObj(JSONObject jsonObj, Class<T> cls) {
    T result = null;

    try {
        Constructor<T> constructor = cls.getDeclaredConstructor();
        constructor.setAccessible(true);
        result = (T) constructor.newInstance();
        Iterator<?> i = jsonObj.keys();

        while (i.hasNext()) {
            String k = (String) i.next();
            Object val = jsonObj.get(k);

            try {
                Field field = cls.getField(k);
                Object converted = valToType(val, field.getGenericType());

                if (converted == null) {
                    if (!field.getType().isPrimitive()) {
                        field.set(result, null);
                    } else {
                        throw new TypeMismatchException(
                                String.format("Type %s cannot be set to null.", field.getType()));
                    }
                } else {
                    if (converted instanceof List && field.getType().isAssignableFrom(List.class)) {
                        // Class can define their own favorite
                        // implementation of List. In which case the field
                        // still need to be defined as List, but it can be
                        // initialized with a placeholder instance of any of
                        // the List implementations (eg. ArrayList).
                        Object existing = field.get(result);
                        if (existing != null) {
                            ((List<?>) existing).clear();

                            // Just because I don't want javac to complain
                            // about unsafe operations. So I'm gonna use
                            // more reflection, HA!
                            Method addAll = existing.getClass().getMethod("addAll", Collection.class);
                            addAll.invoke(existing, converted);
                        } else {
                            field.set(result, converted);
                        }
                    } else {
                        field.set(result, converted);
                    }
                }
            } catch (NoSuchFieldException e) {
                // Ignore.
            } catch (IllegalAccessException e) {
                // Ignore.
            } catch (IllegalArgumentException e) {
                // Ignore.
            }
        }
    } catch (JSONException e) {
        throw new ParserException(e);
    } catch (NoSuchMethodException e) {
        throw new ClassInstantiationException("Failed to retrieve constructor for " + cls.toString()
                + ", make sure it's not an inner class.");
    } catch (InstantiationException e) {
        throw new ClassInstantiationException(cls);
    } catch (IllegalAccessException e) {
        throw new ClassInstantiationException(cls);
    } catch (InvocationTargetException e) {
        throw new ClassInstantiationException(cls);
    }

    return result;
}

From source file:info.guardianproject.netcipher.web.WebkitProxy.java

@TargetApi(19)
private static boolean setKitKatProxy(String appClass, Context appContext, String host, int port) {
    //Context appContext = webView.getContext().getApplicationContext();

    if (host != null) {
        System.setProperty("http.proxyHost", host);
        System.setProperty("http.proxyPort", port + "");
        System.setProperty("https.proxyHost", host);
        System.setProperty("https.proxyPort", port + "");
    }/*www. jav a2  s. com*/

    try {
        Class applictionCls = Class.forName(appClass);
        Field loadedApkField = applictionCls.getField("mLoadedApk");
        loadedApkField.setAccessible(true);
        Object loadedApk = loadedApkField.get(appContext);
        Class loadedApkCls = Class.forName("android.app.LoadedApk");
        Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
        receiversField.setAccessible(true);
        ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object rec : ((ArrayMap) receiverMap).keySet()) {
                Class clazz = rec.getClass();
                if (clazz.getName().contains("ProxyChangeListener")) {
                    Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
                    Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);

                    if (host != null) {
                        /*********** optional, may be need in future *************/
                        final String CLASS_NAME = "android.net.ProxyProperties";
                        Class cls = Class.forName(CLASS_NAME);
                        Constructor constructor = cls.getConstructor(String.class, Integer.TYPE, String.class);
                        constructor.setAccessible(true);
                        Object proxyProperties = constructor.newInstance(host, port, null);
                        intent.putExtra("proxy", (Parcelable) proxyProperties);
                        /*********** optional, may be need in future *************/
                    }

                    onReceiveMethod.invoke(rec, appContext, intent);
                }
            }
        }
        return true;
    } catch (ClassNotFoundException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (NoSuchFieldException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (IllegalAccessException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (IllegalArgumentException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (NoSuchMethodException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (InvocationTargetException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (InstantiationException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    }
    return false;
}

From source file:wicket.util.lang.PropertyResolver.java

/**
 * @param clz// w  ww.jav  a  2 s .com
 * @param expression
 * @return introspected field
 */
private static Field findField(Class<? extends Object> clz, String expression) {
    Field field = null;
    try {
        field = clz.getField(expression);
    } catch (Exception e) {
        log.debug("Cannot find field " + clz + "." + expression, e);
    }
    return field;
}

From source file:info.guardianproject.netcipher.webkit.WebkitProxy.java

@TargetApi(19)
private static boolean setKitKatProxy(String appClass, Context appContext, String host, int port) {
    //Context appContext = webView.getContext().getApplicationContext();

    if (host != null) {
        System.setProperty("http.proxyHost", host);
        System.setProperty("http.proxyPort", Integer.toString(port));
        System.setProperty("https.proxyHost", host);
        System.setProperty("https.proxyPort", Integer.toString(port));
    }//  ww  w .ja v  a 2  s .  c o m

    try {
        Class applictionCls = Class.forName(appClass);
        Field loadedApkField = applictionCls.getField("mLoadedApk");
        loadedApkField.setAccessible(true);
        Object loadedApk = loadedApkField.get(appContext);
        Class loadedApkCls = Class.forName("android.app.LoadedApk");
        Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
        receiversField.setAccessible(true);
        ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object rec : ((ArrayMap) receiverMap).keySet()) {
                Class clazz = rec.getClass();
                if (clazz.getName().contains("ProxyChangeListener")) {
                    Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
                    Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);

                    if (host != null) {
                        /*********** optional, may be need in future *************/
                        final String CLASS_NAME = "android.net.ProxyProperties";
                        Class cls = Class.forName(CLASS_NAME);
                        Constructor constructor = cls.getConstructor(String.class, Integer.TYPE, String.class);
                        constructor.setAccessible(true);
                        Object proxyProperties = constructor.newInstance(host, port, null);
                        intent.putExtra("proxy", (Parcelable) proxyProperties);
                        /*********** optional, may be need in future *************/
                    }

                    onReceiveMethod.invoke(rec, appContext, intent);
                }
            }
        }
        return true;
    } catch (ClassNotFoundException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (NoSuchFieldException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (IllegalAccessException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (IllegalArgumentException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (NoSuchMethodException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (InvocationTargetException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (InstantiationException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    }
    return false;
}

From source file:net.ostis.sc.memory.SCKeynodesBase.java

protected static void init(SCSession session, Class<? extends SCKeynodesBase> klass) {
    if (log.isDebugEnabled())
        log.debug("Start retrieving keynodes for " + klass);

    try {/*from   www.ja  v a 2 s  .c  om*/
        //
        // Search default segment for keynodes
        //
        SCSegment defaultSegment = null;
        {
            DefaultSegment annotation = klass.getAnnotation(DefaultSegment.class);
            if (annotation != null) {
                defaultSegment = session.openSegment(annotation.value());
                Validate.notNull(defaultSegment, "Default segment \"{0}\" not found", annotation.value());
                klass.getField(annotation.fieldName()).set(null, defaultSegment);
            }
        }

        Field[] fields = klass.getFields();
        for (Field field : fields) {
            int modifiers = field.getModifiers();

            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                Class<?> type = field.getType();
                if (type.equals(SCSegment.class)) {
                    //
                    // We have segment field. Load segment by uri.
                    //
                    SegmentURI annotation = field.getAnnotation(SegmentURI.class);

                    if (annotation != null) {
                        String uri = annotation.value();
                        SCSegment segment = session.openSegment(uri);
                        field.set(null, segment);
                    } else {
                        // May be it already has value?
                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have value");
                        }
                    }
                } else {
                    if (!(checkKeynode(session, defaultSegment, field) || checkKeynodeURI(session, field)
                            || checkKeynodesNumberPatternURI(session, klass, field))) {

                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have annotations and value");
                        }

                    }
                }
            }
        }
    } catch (Exception e) {
        // TODO: handle
        e.printStackTrace();
    }
}

From source file:org.apache.storm.config.ConfigUtil.java

/**
 * Create a mapping of config-string -> validator Config fields must have a
 * SCHEMA field defined// ww w.  ja v a2  s .  co m
 * 
 * @return
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
@ClojureClass(className = "backtype.storm.config#CONFIG-SCHEMA-MAP")
public static Map<Object, FieldValidator> configSchemaMap()
        throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Config config = new Config();
    Class<?> configClass = config.getClass();
    Field[] fields = configClass.getFields();
    Map<Object, FieldValidator> result = new HashMap<Object, FieldValidator>();
    for (Field field : fields) {

        String configString = field.getName();
        Pattern p = Pattern.compile(".*_SCHEMA$");
        Matcher m = p.matcher(configString);
        if (!m.matches()) {
            Object valid = configClass.getField(configString + "_SCHEMA").get(null);
            if (null != valid) {
                Object key = field.get(null);
                FieldValidator fieldValidator = getFieldValidator(valid);
                result.put(key, fieldValidator);
            }
        }
    }
    return result;
}

From source file:org.eclipse.wb.internal.swing.laf.LafSupport.java

/**
 * Applies commands for modifying list of LAFs.
 *//*  w  w w .  j a v a2s .  c  o  m*/
private static void commands_apply() {
    try {
        // prepare mapping: id -> command class
        if (m_idToCommandClass == null) {
            m_idToCommandClass = Maps.newTreeMap();
            for (Class<? extends Command> commandClass : m_commandClasses) {
                String id = (String) commandClass.getField("ID").get(null);
                m_idToCommandClass.put(id, commandClass);
            }
        }
        // read commands
        m_commands = Lists.newArrayList();
        File commandsFile = commands_getFile();
        if (commandsFile.exists()) {
            FileInputStream inputStream = new FileInputStream(commandsFile);
            try {
                SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
                parser.parse(inputStream, new DefaultHandler() {
                    @Override
                    public void startElement(String uri, String localName, String name, Attributes attributes) {
                        try {
                            // prepare command class
                            Class<? extends Command> commandClass;
                            {
                                commandClass = m_idToCommandClass.get(name);
                                if (commandClass == null) {
                                    return;
                                }
                            }
                            // create command
                            Command command;
                            {
                                Constructor<? extends Command> constructor = commandClass
                                        .getConstructor(new Class[] { Attributes.class });
                                command = constructor.newInstance(new Object[] { attributes });
                            }
                            // add command
                            commands_addExecute(command);
                        } catch (Throwable e) {
                        }
                    }
                });
            } finally {
                inputStream.close();
            }
        }
    } catch (Throwable e) {
    }
}

From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java

private static Object inspect(Object o, Class<?> clazz, String field, AtomicReference<Type> type) {
    try {//from ww  w  . j a v  a 2 s  .c  o m
        try {
            Field f = clazz.getField(field);
            type.set(f.getGenericType());
            return f.get(o);
        } catch (NoSuchFieldException x) {
            // OK, check for getter instead
        }
        try {
            Method m = clazz.getMethod("get" + Character.toUpperCase(field.charAt(0)) + field.substring(1));
            type.set(m.getGenericReturnType());
            return m.invoke(o);
        } catch (NoSuchMethodException x) {
            // one more check
        }
        try {
            type.set(boolean.class);
            return clazz.getMethod("is" + Character.toUpperCase(field.charAt(0)) + field.substring(1))
                    .invoke(o);
        } catch (NoSuchMethodException x) {
            throw new UnsupportedOperationException(
                    "no public field " + field + " (or getter method) found in " + clazz);
        }
    } catch (UnsupportedOperationException x) {
        throw x;
    } catch (Exception x) {
        throw new UnsupportedOperationException(x);
    }
}

From source file:ca.uhn.fhir.context.ModelScanner.java

@SuppressWarnings("unchecked")
static IValueSetEnumBinder<Enum<?>> getBoundCodeBinder(Field theNext) {
    Class<?> bound = getGenericCollectionTypeOfCodedField(theNext);
    if (bound == null) {
        throw new ConfigurationException("Field '" + theNext + "' has no parameter for "
                + BoundCodeDt.class.getSimpleName() + " to determine enum type");
    }/*from  w w w  .  j  a va 2 s. c  om*/

    String fieldName = "VALUESET_BINDER";
    try {
        Field bindingField = bound.getField(fieldName);
        return (IValueSetEnumBinder<Enum<?>>) bindingField.get(null);
    } catch (Exception e) {
        throw new ConfigurationException("Field '" + theNext + "' has type parameter "
                + bound.getCanonicalName()
                + " but this class has no valueset binding field (must have a field called " + fieldName + ")",
                e);
    }
}

From source file:edu.cmu.cs.lti.util.uima.UimaConvenience.java

/**
 * Returns a list of annotations of the specified type in the specified CAS. The difference of
 * this with JCasUtil.select is that this method will store everything into a list first, so if
 * modifying stuff, it won't raise ConcurrentModificationException
 * //from   ww w . j  av  a  2 s  .co m
 * @param aJCas
 * @param clazz
 * @return a list of annotations of the specified type in the specified CAS
 */
public static <T extends TOP> List<T> getAnnotationList(JCas aJCas, final Class<T> clazz) {
    try {
        // TODO: The integer field 'type' and 'typeIndexID' take the same
        // value as those of its parent
        // type. We need to fix the code below so it gets only the specified
        // annotation.
        final int type = clazz.getField("type").getInt(clazz);

        List<T> annotationList = new ArrayList<T>();
        Iterator<?> annotationIter = aJCas.getJFSIndexRepository().getAllIndexedFS(type);
        while (annotationIter.hasNext()) {
            T annotation = (T) annotationIter.next();
            annotationList.add(annotation);
        }
        return annotationList;
    } catch (SecurityException e) {
        throw new CASRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new CASRuntimeException(e);
    } catch (NoSuchFieldException e) {
        throw new CASRuntimeException(e);
    }
}