Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:Main.java

/**
 * @param context//from w  w  w  .j av  a  2  s.c  o m
 *            if null, use the default format (Mozilla/5.0 (Linux; U;
 *            Android %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0
 *            %sSafari/534.30).
 * @return
 */

public static String getUserAgent(Context context) {
    String webUserAgent = null;
    if (context != null) {
        try {
            Class<?> sysResCls = Class.forName("com.android.internal.R$string");
            Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
            Integer resId = (Integer) webUserAgentField.get(null);
            webUserAgent = context.getString(resId);
        } catch (Throwable ignored) {
        }
    }
    if (TextUtils.isEmpty(webUserAgent)) {
        webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1";
    }

    Locale locale = Locale.getDefault();
    StringBuffer buffer = new StringBuffer();
    // Add version
    final String version = Build.VERSION.RELEASE;
    if (version.length() > 0) {
        buffer.append(version);
    } else {
        // default to "1.0"
        buffer.append("1.0");
    }
    buffer.append("; ");
    final String language = locale.getLanguage();
    if (language != null) {
        buffer.append(language.toLowerCase());
        final String country = locale.getCountry();
        if (country != null) {
            buffer.append("-");
            buffer.append(country.toLowerCase());
        }
    } else {
        // default to "en"
        buffer.append("en");
    }
    // add the model for the release build
    if ("REL".equals(Build.VERSION.CODENAME)) {
        final String model = Build.MODEL;
        if (model.length() > 0) {
            buffer.append("; ");
            buffer.append(model);
        }
    }
    final String id = Build.ID;
    if (id.length() > 0) {
        buffer.append(" Build/");
        buffer.append(id);
    }
    return String.format(webUserAgent, buffer, "Mobile ");
}

From source file:Main.java

static Field getField(Class<?> clz, final String fldName) {
    if (clz == null || TextUtils.isEmpty(fldName)) {
        return null;
    }/*from  ww  w  .  j a  va2s  . co m*/
    Field fld = null;
    try {
        fld = clz.getDeclaredField(fldName);
        fld.setAccessible(true);
    } catch (NoSuchFieldException e) {
        Log.d(TAG, e.getMessage(), e);
    }
    return fld;
}

From source file:Main.java

public static Field getField(Class<?> sourceClass, String fieldName, boolean isFindDeclaredField,
        boolean isUpwardFind) {
    Field field = null;//from  w ww. j a  v  a2s .  c o  m
    try {
        field = isFindDeclaredField ? sourceClass.getDeclaredField(fieldName) : sourceClass.getField(fieldName);
    } catch (NoSuchFieldException e1) {
        if (isUpwardFind) {
            Class<?> classs = sourceClass.getSuperclass();
            while (field == null && classs != null) {
                try {
                    field = isFindDeclaredField ? classs.getDeclaredField(fieldName)
                            : classs.getField(fieldName);
                } catch (NoSuchFieldException e11) {
                    classs = classs.getSuperclass();
                }
            }
        }
    }
    return field;
}

From source file:Main.java

@SuppressLint("NewApi")
@SuppressWarnings("all")
private static boolean setProxyKK(WebView webView, String host, int port, String applicationClassName) {
    Context appContext = webView.getContext().getApplicationContext();
    if (null == host) {
        System.clearProperty("http.proxyHost");
        System.clearProperty("http.proxyPort");
        System.clearProperty("https.proxyHost");
        System.clearProperty("https.proxyPort");
    } else {/*from w w  w.ja v  a 2s.c om*/
        System.setProperty("http.proxyHost", host);
        System.setProperty("http.proxyPort", port + "");
        System.setProperty("https.proxyHost", host);
        System.setProperty("https.proxyPort", port + "");
    }
    try {
        Class applictionCls = Class.forName(applicationClassName);
        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);
        Map receivers = (Map) receiversField.get(loadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object rec : ((Map) 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);

                    /*********** 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);
                }
            }
        }
        Log.d(LOG_TAG, "Setting proxy with >= 4.4 API successful!");
        return true;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.haulmont.cuba.gui.icons.IconsImpl.java

protected static String resolveIcon(String iconName) {
    String iconSource = null;//from   ww  w.j a v a  2s . com

    for (Class<? extends Icon> iconSet : iconSets) {
        try {
            Object obj = iconSet.getDeclaredField(iconName).get(null);
            iconSource = ((Icon) obj).source();
        } catch (IllegalAccessException | NoSuchFieldException ignored) {
            // must be ignored, because some icon sets in the sequence may not contain the icon, e.g.:
            // assuming icon sets CubaIcon > MyCompIcon > MyAppIcon,
            // CubaIcon.OK - defined, MyCompIcon.OK - overrides, MyAppIcon.OK - not defined
            // then using MyCompIcon.OK
        }
    }

    return iconSource;
}

From source file:Main.java

/**
 * @param context if null, use the default format
 *                (Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 %sSafari/534.30).
 * @return/* ww w  .  j  a va  2 s .c  om*/
 */
public static String getUserAgent(Context context) {
    String webUserAgent = null;
    if (context != null) {
        try {
            Class sysResCls = Class.forName("com.android.internal.R$string");
            Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
            Integer resId = (Integer) webUserAgentField.get(null);
            webUserAgent = context.getString(resId);
        } catch (Throwable ignored) {
        }
    }
    if (TextUtils.isEmpty(webUserAgent)) {
        webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1";
    }

    Locale locale = Locale.getDefault();
    StringBuffer buffer = new StringBuffer();
    // Add version
    final String version = Build.VERSION.RELEASE;
    if (version.length() > 0) {
        buffer.append(version);
    } else {
        // default to "1.0"
        buffer.append("1.0");
    }
    buffer.append("; ");
    final String language = locale.getLanguage();
    if (language != null) {
        buffer.append(language.toLowerCase());
        final String country = locale.getCountry();
        if (country != null) {
            buffer.append("-");
            buffer.append(country.toLowerCase());
        }
    } else {
        // default to "en"
        buffer.append("en");
    }
    // add the model for the release build
    if ("REL".equals(Build.VERSION.CODENAME)) {
        final String model = Build.MODEL;
        if (model.length() > 0) {
            buffer.append("; ");
            buffer.append(model);
        }
    }
    final String id = Build.ID;
    if (id.length() > 0) {
        buffer.append(" Build/");
        buffer.append(id);
    }
    return String.format(webUserAgent, buffer, "Mobile ");
}

From source file:com.cassius.spring.assembly.test.common.reflect.FieldWriter.java

/**
 * New instance./* w  w w.  j a  v a  2 s .  c  o  m*/
 *
 * @param object the object
 * @param fieldName the field name
 * @param value the value
 * @return the field writer
 * @throws NoSuchFieldException the no such field exception
 */
public static FieldWriter newInstance(Object object, String fieldName, Object value)
        throws NoSuchFieldException {
    Class<?> clazz = object.getClass();
    while (clazz != Object.class) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                return new FieldWriter(object, field, value);
            }
        } catch (NoSuchFieldException ignore) {
        }
        clazz = clazz.getSuperclass();
    }
    throw new NoSuchFieldException(fieldName + "not exist");
}

From source file:com.cassius.spring.assembly.test.common.reflect.FieldReader.java

/**
 * New instance.//from w ww  .  j  a v a 2  s  . co  m
 *
 * @param object the object
 * @param fieldName the field name
 * @return the field reader
 * @throws NoSuchFieldException the no such field exception
 */
public static FieldReader newInstance(Object object, String fieldName) throws NoSuchFieldException {
    Class<?> clazz = object.getClass();
    while (clazz != Object.class) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                return newInstance(object, field);
            }
        } catch (NoSuchFieldException ignore) {
        }
        clazz = clazz.getSuperclass();
    }
    throw new NoSuchFieldException(fieldName + "not exist");
}

From source file:com.github.jknack.handlebars.helper.DefaultFilterHelper.java

private static <T> String getFieldValue(T input, String fielName) {
    String typeVal = "";
    try {/*from w w  w .j  ava2  s .c  o m*/
        Class<T> clazz = (Class<T>) input.getClass();
        Field field = clazz.getDeclaredField(fielName);
        field.setAccessible(true);
        typeVal = (String) field.get(input);
    } catch (Exception ex) {

    }
    return typeVal;
}

From source file:Main.java

private static List<Activity> getAllActivitiesHack() throws ClassNotFoundException, NoSuchMethodException,
        NoSuchFieldException, IllegalAccessException, InvocationTargetException {
    Class activityThreadClass = Class.forName("android.app.ActivityThread");
    Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
    Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
    activitiesField.setAccessible(true);
    Map activities = (Map) activitiesField.get(activityThread);
    List<Activity> activitiesList = new ArrayList<Activity>(activities.size());

    for (Object activityRecord : activities.values()) {
        Class activityRecordClass = activityRecord.getClass();
        Field activityField = activityRecordClass.getDeclaredField("activity");
        activityField.setAccessible(true);
        Activity activity = (Activity) activityField.get(activityRecord);
        activitiesList.add(activity);/*from   w  ww. ja v a 2s .  c  o  m*/
    }

    return activitiesList;
}