Example usage for java.lang.reflect Method setAccessible

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

Introduction

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

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:kelly.util.BeanUtils.java

/**
 * Copy the property values of the given source bean into the given target bean.
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean/*from  w  ww.j a v  a2  s .c o  m*/
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyProperties(Object source, Object target, Class<?> editable,
        String... ignoreProperties) {

    Validate.notNull(source, "Source must not be null");
    Validate.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null
                        && writeMethod.getParameterTypes()[0].isAssignableFrom(readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    } catch (Throwable ex) {
                        throw new BeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:com.github.gekoh.yagen.hibernate.PatchHibernateMappingClasses.java

private static boolean alreadyLoaded(String className) throws Exception {
    java.lang.reflect.Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass",
            new Class[] { String.class });
    m.setAccessible(true);
    ClassLoader cl = PatchHibernateMappingClasses.class.getClassLoader();
    Object test1 = m.invoke(cl, className);
    return test1 != null;
}

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

private static void clearReferencesStopTimerThread(Thread thread) {

    // Need to get references to:
    // - newTasksMayBeScheduled field
    // - queue field
    // - queue.clear()

    try {//  w  ww .  ja v  a  2 s  .  co  m
        Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled");
        newTasksMayBeScheduledField.setAccessible(true);
        Field queueField = thread.getClass().getDeclaredField("queue");
        queueField.setAccessible(true);

        Object queue = queueField.get(thread);

        Method clearMethod = queue.getClass().getDeclaredMethod("clear");
        clearMethod.setAccessible(true);

        synchronized (queue) {
            newTasksMayBeScheduledField.setBoolean(thread, false);
            clearMethod.invoke(queue);
            queue.notify(); // In case queue was already empty.
        }

        if (logger.isLoggable(Level.FINE))
            logger.fine("A web application appears to have started a TimerThread named [" + thread.getName()
                    + "] via the java.util.Timer API but has failed to stop it. To prevent a memory leak, the timer (and hence the associated thread) has been forcibly cancelled.");

    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to terminate TimerThread named [" + thread.getName() + "]", e);
    }
}

From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java

/**
 * Fetches the methods on a class that are annotated with SpringBean. The first time it
 * is called for a particular class it will introspect the class and cache the results.
 * All non-overridden methods are examined, including protected and private methods.
 * If a method is not public an attempt it made to make it accessible - if it fails
 * it is removed from the collection and an error is logged.
 *
 * @param clazz the class on which to look for SpringBean annotated methods
 * @return the collection of methods with the annotation
 *//*w w w  .jav  a2  s . co  m*/
protected static Collection<Method> getMethods(Class<?> clazz) {
    Collection<Method> methods = methodMap.get(clazz);
    if (methods == null) {
        methods = ReflectUtil.getMethods(clazz);
        Iterator<Method> iterator = methods.iterator();

        while (iterator.hasNext()) {
            Method method = iterator.next();
            if (!method.isAnnotationPresent(SpringBean.class)) {
                iterator.remove();
            } else {
                // If the method isn't public, try to make it accessible
                if (!method.isAccessible()) {
                    try {
                        method.setAccessible(true);
                    } catch (SecurityException se) {
                        throw new StripesRuntimeException("Method " + clazz.getName() + "." + method.getName()
                                + "is marked " + "with @SpringBean and is not public. An attempt to call "
                                + "setAccessible(true) resulted in a SecurityException. Please "
                                + "either make the method public or modify your JVM security "
                                + "policy to allow Stripes to setAccessible(true).", se);
                    }
                }

                // Ensure the method has only the one parameter
                if (method.getParameterTypes().length != 1) {
                    throw new StripesRuntimeException(
                            "A method marked with @SpringBean must have exactly one parameter: "
                                    + "the bean to be injected. Method [" + method.toGenericString() + "] has "
                                    + method.getParameterTypes().length + " parameters.");
                }
            }
        }

        methodMap.put(clazz, methods);
    }

    return methods;
}

From source file:org.zywx.wbpalmstar.plugin.uexiconlist.utils.IconListUtils.java

/**
 * ???//  w  ww  .  j  av a2s  .  c  o m
 * 
 * @param className
 *            ??
 * @param methodName
 *            ??
 * @param parmTypeList
 *            ?
 * @return
 */
public static Method getReflectionMethod(String className, String methodName, Class<?>[] parmTypeList) {
    Method mMethod = null;
    try {
        Class<?> mClass = Class.forName(className);
        try {
            /** ?methodName, parmList?public?public */
            mMethod = mClass.getDeclaredMethod(methodName, parmTypeList);
            mMethod.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return mMethod;
}

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

private static void clearThreadLocalMap(Object map, Field internalTableField, ClassLoader classLoader)
        throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException, InvocationTargetException {
    if (map != null) {
        Method mapRemove = map.getClass().getDeclaredMethod("remove", ThreadLocal.class);
        mapRemove.setAccessible(true);
        final Object[] table = (Object[]) internalTableField.get(map);
        int staleEntriesCount = 0;
        if (table != null) {
            for (int j = 0; j < table.length; j++) {
                final Object tableEntry = table[j];
                if (tableEntry != null) {
                    boolean remove = false;
                    // Check the key
                    Object key = ((Reference<?>) tableEntry).get();
                    if (classLoader.equals(key)
                            || (key != null && classLoader == key.getClass().getClassLoader())) {
                        remove = true;//from   www.ja  v  a 2 s.  c om
                    }
                    // Check the value
                    Field valueField = tableEntry.getClass().getDeclaredField("value");
                    valueField.setAccessible(true);
                    Object value = valueField.get(tableEntry);
                    if (classLoader.equals(value)
                            || (value != null && classLoader == value.getClass().getClassLoader())) {
                        remove = true;
                    }
                    if (remove) {
                        Object[] args = new Object[4];
                        if (key != null) {
                            args[0] = key.getClass().getCanonicalName();
                            args[1] = key.toString();
                        }
                        if (value != null) {
                            args[2] = value.getClass().getCanonicalName();
                            args[3] = value.toString();
                        }
                        if (value == null) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("A created a ThreadLocal with key of type [" + args[0]
                                        + "] (value [" + args[1]
                                        + "]). The ThreadLocal has been correctly set to null and the key will be removed by GC. However, to simplify the process of tracing memory leaks, the key has been forcibly removed.");
                            }
                        } else {
                            if (logger.isLoggable(Level.FINE))
                                logger.fine("A created ThreadLocal with key of type [" + args[0] + "] (value ["
                                        + args[1] + "]) and a value of type [" + args[2] + "] (value ["
                                        + args[3]
                                        + "]) but failed to remove it when class loader is removed. To prevent a memory leak, the ThreadLocal has been forcibly removed.");
                        }
                        if (key == null) {
                            staleEntriesCount++;
                        } else {
                            mapRemove.invoke(map, key);
                        }
                    }
                }
            }
        }
        if (staleEntriesCount > 0) {
            Method mapRemoveStale = map.getClass().getDeclaredMethod("expungeStaleEntries");
            mapRemoveStale.setAccessible(true);
            mapRemoveStale.invoke(map);
        }
    }
}

From source file:Main.java

/**
 * Because of a BUG of Android (API 13-),
 * get signature info by using "getPackageArchiveInfo" of "PackageManager"
 * always causes "NullPointerException".
 * Lack of code in method "getPackageArchiveInfo":
 *     if ((flags & GET_SIGNATURES) != 0)
 *     {/*from  ww w  .j  a  v  a  2 s. c om*/
 *         packageParser.collectCertificates(pkg, 0);
 *     }
 */
@SuppressWarnings("unchecked")
public static PackageInfo getPackageArchiveInfo(String archiveFilePath, int flags) {
    try {
        Class packageParserClass = Class.forName("android.content.pm.PackageParser");
        Class[] innerClasses = packageParserClass.getDeclaredClasses();
        Class packageParserPackageClass = null;
        for (Class innerClass : innerClasses) {
            if (0 == innerClass.getName().compareTo("android.content.pm.PackageParser$Package")) {
                packageParserPackageClass = innerClass;
                break;
            }
        }
        Constructor packageParserConstructor = packageParserClass.getConstructor(String.class);
        Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class,
                String.class, DisplayMetrics.class, int.class);
        Method collectCertificatesMethod = packageParserClass.getDeclaredMethod("collectCertificates",
                packageParserPackageClass, int.class);
        Method generatePackageInfoMethod = packageParserClass.getDeclaredMethod("generatePackageInfo",
                packageParserPackageClass, int[].class, int.class, long.class, long.class);
        packageParserConstructor.setAccessible(true);
        parsePackageMethod.setAccessible(true);
        collectCertificatesMethod.setAccessible(true);
        generatePackageInfoMethod.setAccessible(true);

        Object packageParser = packageParserConstructor.newInstance(archiveFilePath);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        displayMetrics.setToDefaults();

        final File sourceFile = new File(archiveFilePath);

        Object pkg = parsePackageMethod.invoke(packageParser, sourceFile, archiveFilePath, displayMetrics, 0);
        if (pkg == null) {
            return null;
        }

        if ((flags & PackageManager.GET_SIGNATURES) != 0) {
            collectCertificatesMethod.invoke(packageParser, pkg, 0);
        }

        return (PackageInfo) generatePackageInfoMethod.invoke(null, pkg, null, flags, 0, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Main.java

/**
 * Returns an array of all methods in a class with the specified parameter types.
 *
 * The return type is optional, it will not be compared if it is {@code null}.
 * Use {@code void.class} if you want to search for methods returning nothing.
 *//*from  w ww  .  ja va2s . c  o m*/
public static Method[] findMethodsByExactParameters(Class<?> clazz, Class<?> returnType,
        Class<?>... parameterTypes) {
    List<Method> result = new LinkedList<Method>();
    for (Method method : clazz.getDeclaredMethods()) {
        if (returnType != null && returnType != method.getReturnType())
            continue;

        Class<?>[] methodParameterTypes = method.getParameterTypes();
        if (parameterTypes.length != methodParameterTypes.length)
            continue;

        boolean match = true;
        for (int i = 0; i < parameterTypes.length; i++) {
            if (parameterTypes[i] != methodParameterTypes[i]) {
                match = false;
                break;
            }
        }

        if (!match)
            continue;

        method.setAccessible(true);
        result.add(method);
    }
    return result.toArray(new Method[result.size()]);
}

From source file:cascading.util.Util.java

public static Object invokeStaticMethod(Class type, String methodName, Object[] parameters,
        Class[] parameterTypes) {
    try {/*from w  ww.j  a v a 2 s  .  c om*/
        Method method = type.getDeclaredMethod(methodName, parameterTypes);

        method.setAccessible(true);

        return method.invoke(null, parameters);
    } catch (Exception exception) {
        throw new FlowException("unable to invoke static method: " + type.getName() + "." + methodName,
                exception);
    }
}

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

/**
 * Deregister any JDBC drivers registered by the webapp that the webapp forgot. This is made
 * unnecessary complex because a) DriverManager checks the class loader of the calling class (it
 * would be much easier if it checked the context class loader) b) using reflection would create
 * a dependency on the DriverManager implementation which can, and has, changed.
 *
 * We can't just create an instance of JdbcLeakPrevention as it will be loaded by the common
 * class loader (since it's .class file is in the $CATALINA_HOME/lib directory). This would fail
 * DriverManager's check on the class loader of the calling class. So, we load the bytes via our
 * parent class loader but define the class with this class loader so the JdbcLeakPrevention
 * looks like a webapp class to the DriverManager.
 *
 * If only apps cleaned up after themselves...
 *///from   w  w w .j  a  v a2s.  c  o  m
private final static void clearReferencesJdbc(ClassLoader classLoader) {
    InputStream is = classLoader.getResourceAsStream("com/gigaspaces/internal/utils/JdbcLeakPrevention.class");
    // We know roughly how big the class will be (~ 1K) so allow 2k as a
    // starting point
    byte[] classBytes = new byte[2048];
    int offset = 0;
    try {
        int read = is.read(classBytes, offset, classBytes.length - offset);
        while (read > -1) {
            offset += read;
            if (offset == classBytes.length) {
                // Buffer full - double size
                byte[] tmp = new byte[classBytes.length * 2];
                System.arraycopy(classBytes, 0, tmp, 0, classBytes.length);
                classBytes = tmp;
            }
            read = is.read(classBytes, offset, classBytes.length - offset);
        }
        Method defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", String.class,
                byte[].class, int.class, int.class);
        defineClassMethod.setAccessible(true);
        Class<?> lpClass = (Class<?>) defineClassMethod.invoke(classLoader,
                "com.gigaspaces.internal.utils.JdbcLeakPrevention", classBytes, 0, offset);
        Object obj = lpClass.newInstance();
        @SuppressWarnings("unchecked")
        List<String> driverNames = (List<String>) obj.getClass().getMethod("clearJdbcDriverRegistrations")
                .invoke(obj);
        for (String name : driverNames) {
            if (logger.isLoggable(Level.FINE))
                logger.fine("A class loader registered the JDBC driver [" + name
                        + "] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.");
        }
    } catch (Exception e) {
        //So many things to go wrong above...
        if (logger.isLoggable(Level.FINE))
            logger.log(Level.FINE, "JDBC driver de-registration failed", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
}