Example usage for java.lang.reflect Field setAccessible

List of usage examples for java.lang.reflect Field setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Field setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:com.facebook.hiveio.log.HiveLogHelpers.java

/**
 * Add class logger to the list of logs/* w ww.  jav a2  s .co m*/
 *
 * @param logs List of logs
 * @param klass Class whose logger we want to add
 */
private static void addPrivateStaticLog(List<Log> logs, Class<?> klass) {
    try {
        Field logField = klass.getDeclaredField("LOG");
        logField.setAccessible(true);
        Log driverLog = (Log) logField.get(null);
        logs.add(driverLog);
    } catch (IllegalAccessException e) {
        LOG.error("Could not get LOG from Hive ql.Driver", e);
    } catch (NoSuchFieldException e) {
        LOG.error("Could not get LOG from Hive ql.Driver", e);
    }
}

From source file:Main.java

public static boolean isMeizuSecurity(Context context) {
    if (!isSecVer(context)) {
        return false;
    }/*from   ww  w  . ja  v  a 2 s.  c  o m*/
    Boolean valueOf = Boolean.valueOf(false);
    try {
        Boolean bool;
        Class cls = Class.forName("android.os.Build");
        Field field = cls.getField("MeizuSecurity");
        field.setAccessible(true);
        bool = (Boolean) field.get(cls);
        return bool;
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (Error e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return valueOf.booleanValue();
}

From source file:Main.java

public final static void fixPopupWindow(final PopupWindow window) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        try {/*from  w  w w.  j av a  2  s.c  o  m*/
            final Field mAnchorField = PopupWindow.class.getDeclaredField("mAnchor");
            mAnchorField.setAccessible(true);
            Field mOnScrollChangedListenerField = PopupWindow.class
                    .getDeclaredField("mOnScrollChangedListener");
            mOnScrollChangedListenerField.setAccessible(true);

            final OnScrollChangedListener mOnScrollChangedListener = (OnScrollChangedListener) mOnScrollChangedListenerField
                    .get(window);

            OnScrollChangedListener newListener = new OnScrollChangedListener() {
                public void onScrollChanged() {
                    try {
                        WeakReference<?> mAnchor = WeakReference.class.cast(mAnchorField.get(window));
                        Object anchor = mAnchor != null ? mAnchor.get() : null;

                        if (anchor == null) {
                            return;
                        } else {
                            mOnScrollChangedListener.onScrollChanged();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            mOnScrollChangedListenerField.set(window, newListener);
        } catch (Exception e) {
        }
    }
}

From source file:com.codebase.foundation.classloader.xbean.ClassLoaderUtil.java

/**
 * Clears the caches maintained by the SunVM object stream implementation.  This method uses reflection and
 * setAccessable to obtain access to the Sun cache.  The cache is locked with a synchronize monitor and cleared.
 * This method completely clears the class loader cache which will impact performance of object serialization.
 * @param clazz the name of the class containing the cache field
 * @param fieldName the name of the cache field
 *///from w w w .java  2 s  .  c o m
@SuppressWarnings("all")
public static void clearSunSoftCache(Class clazz, String fieldName) {
    Map cache = null;
    try {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        cache = (Map) field.get(null);
    } catch (Throwable ignored) {
        // there is nothing a user could do about this anyway
    }

    if (cache != null) {
        synchronized (cache) {
            cache.clear();
        }
    }
}

From source file:Main.java

public static Service createService(Context context, ServiceInfo serviceInfo) throws Exception {
    IBinder token = new Binder();

    Class<?> createServiceDataClass = Class.forName("android.app.ActivityThread$CreateServiceData");
    Constructor<?> constructor = createServiceDataClass.getDeclaredConstructor();
    constructor.setAccessible(true);/*ww w . java 2 s .  co m*/
    Object createServiceData = constructor.newInstance();

    Field tokenField = createServiceDataClass.getDeclaredField("token");
    tokenField.setAccessible(true);
    tokenField.set(createServiceData, token);

    serviceInfo.applicationInfo.packageName = context.getPackageName();
    Field infoField = createServiceDataClass.getDeclaredField("info");
    infoField.setAccessible(true);
    infoField.set(createServiceData, serviceInfo);

    Class<?> compatibilityClass = Class.forName("android.content.res.CompatibilityInfo");
    Field defaultCompatibilityField = compatibilityClass.getDeclaredField("DEFAULT_COMPATIBILITY_INFO");
    defaultCompatibilityField.setAccessible(true);
    Object defaultCompatibility = defaultCompatibilityField.get(null);
    defaultCompatibilityField.set(createServiceData, defaultCompatibility);

    Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
    Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
    Object currentActivityThread = currentActivityThreadMethod.invoke(null);

    Method handleCreateServiceMethod = activityThreadClass.getDeclaredMethod("handleCreateService",
            createServiceDataClass);
    handleCreateServiceMethod.setAccessible(true);
    handleCreateServiceMethod.invoke(currentActivityThread, createServiceData);

    Field mServicesField = activityThreadClass.getDeclaredField("mServices");
    mServicesField.setAccessible(true);
    Map mServices = (Map) mServicesField.get(currentActivityThread);
    Service service = (Service) mServices.get(token);
    mServices.remove(token);

    return service;
}

From source file:com.googlecode.easymockrule.EasyMockUtils.java

/**
 * Get the mock control "type" field value or empty string on error.
 * //w  w w.  j  a v  a  2s. com
 * @param mock
 * @return
 */
public static String getMockType(Object mock) {

    try {
        MocksControl mockControl = getMockControl(mock);

        Field mockTypeField = mockControl.getClass().getDeclaredField("type");
        mockTypeField.setAccessible(true);

        MockType mockType = (MockType) mockTypeField.get(mockControl);

        return mockType.toString();

    } catch (Exception e) {
        return StringUtils.EMPTY;
    }
}

From source file:de.erdesignerng.visual.Java3DUtils.java

private static void addLibraryPath(String pathToAdd) throws Exception {
    Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
    usrPathsField.setAccessible(true);

    //get array of paths
    String[] paths = (String[]) usrPathsField.get(null);

    //check if the path to add is already present
    for (String path : paths) {
        if (path.equals(pathToAdd)) {
            return;
        }//from   w  w w . j av a  2 s.  c o m
    }

    //add the new path
    String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
    newPaths[newPaths.length - 1] = pathToAdd;
    usrPathsField.set(null, newPaths);
}

From source file:Main.java

@SuppressLint("UseSparseArrays")
public static ArrayList<String> extractor(Notification notification) {
    ArrayList<String> notifText = new ArrayList<String>();
    RemoteViews views = notification.contentView;
    @SuppressWarnings("rawtypes")
    Class secretClass = views.getClass();

    try {/*  w  w w. j a v  a  2s .  c o m*/

        Field outerFields[] = secretClass.getDeclaredFields();
        for (int i = 0; i < outerFields.length; i++) {

            if (!outerFields[i].getName().equals("mActions"))
                continue;

            outerFields[i].setAccessible(true);

            @SuppressWarnings("unchecked")
            ArrayList<Object> actions = (ArrayList<Object>) outerFields[i].get(views);
            for (Object action : actions) {

                Field innerFields[] = action.getClass().getDeclaredFields();

                Object value = null;
                Integer type = null;
                @SuppressWarnings("unused")
                Integer viewId = null;
                for (Field field : innerFields) {

                    field.setAccessible(true);
                    if (field.getName().equals("value")) {
                        value = field.get(action);
                    } else if (field.getName().equals("type")) {
                        type = field.getInt(action);
                    } else if (field.getName().equals("viewId")) {
                        viewId = field.getInt(action);
                    }
                }

                if (type != null && (type == 9 || type == 10) && value != null) {
                    // System.out.println("Type: " + Integer.toString(type)
                    // + " Value: " + value.toString());
                    if (!notifText.contains(value.toString()))
                        notifText.add(value.toString());
                }

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return notifText;
}

From source file:Main.java

public static void cleanThreadLocals(Thread thread)
        throws NoSuchFieldException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
    if (thread == null)
        return;//from   ww w .ja v  a  2s. c o  m
    Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
    threadLocalsField.setAccessible(true);

    Class<?> threadLocalMapKlazz = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
    Field tableField = threadLocalMapKlazz.getDeclaredField("table");
    tableField.setAccessible(true);

    Object fieldLocal = threadLocalsField.get(thread);
    if (fieldLocal == null) {
        return;
    }
    Object table = tableField.get(fieldLocal);

    int threadLocalCount = Array.getLength(table);

    for (int i = 0; i < threadLocalCount; i++) {
        Object entry = Array.get(table, i);
        if (entry != null) {
            Field valueField = entry.getClass().getDeclaredField("value");
            valueField.setAccessible(true);
            Object value = valueField.get(entry);
            if (value != null) {

                if ("java.util.concurrent.ConcurrentLinkedQueue".equals(value.getClass().getName())
                        || "java.util.concurrent.ConcurrentHashMap".equals(value.getClass().getName())) {
                    valueField.set(entry, null);
                }
            }

        }
    }
}

From source file:Main.java

/**
 * Coverter./*from   w  w  w. jav a2  s .  c  om*/
 *
 * @param object
 *            the object
 * @return the string
 */
@SuppressWarnings("unused")
public static String coverter(Object object) {
    if (object instanceof Object[]) {
        return coverter((Object[]) object);
    }
    if (object instanceof Collection) {
        return coverter((Collection<?>) object);
    }
    StringBuilder strBuilder = new StringBuilder();
    if (isObject(object)) {
        Class<? extends Object> clz = object.getClass();
        Field[] fields = clz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            if (field == null) {
                continue;
            }
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(object);
            } catch (IllegalArgumentException e) {
                continue;
            } catch (IllegalAccessException e) {
                continue;
            }
            strBuilder.append("<").append(fieldName).append(" className=\"").append(value.getClass().getName())
                    .append("\">\n");
            strBuilder.append(value.toString() + "\n");
            strBuilder.append("</").append(fieldName).append(">\n");
        }
    } else if (object == null) {
        strBuilder.append("null");
    } else {
        strBuilder.append(object.toString());
    }
    return strBuilder.toString();
}