Example usage for java.lang.reflect Constructor setAccessible

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

Introduction

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

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Document

A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.

Usage

From source file:org.apache.tez.runtime.library.common.TezRuntimeUtils.java

public static TezTaskOutput instantiateTaskOutputManager(Configuration conf, OutputContext outputContext) {
    Class<?> clazz = conf.getClass(Constants.TEZ_RUNTIME_TASK_OUTPUT_MANAGER, TezTaskOutputFiles.class);
    try {/*from w w w .j a v  a 2  s.c  om*/
        Constructor<?> ctor = clazz.getConstructor(Configuration.class, String.class);
        ctor.setAccessible(true);
        TezTaskOutput instance = (TezTaskOutput) ctor.newInstance(conf, outputContext.getUniqueIdentifier());
        return instance;
    } catch (Exception e) {
        throw new TezUncheckedException("Unable to instantiate configured TezOutputFileManager: "
                + conf.get(Constants.TEZ_RUNTIME_TASK_OUTPUT_MANAGER, TezTaskOutputFiles.class.getName()), e);
    }
}

From source file:com.edmunds.autotest.ClassUtil.java

public static Object instanceClass(Class cls, String msg) {
    if (cls.isInterface()) {
        return Proxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, NOOP_HANDLER);
    } else if (isStandardClass(cls) && hasDefaultConstructor(cls)) {
        try {/*from  w w w. j av a2  s  . co  m*/
            Constructor constructor = getDefaultConstructor(cls);
            constructor.setAccessible(true);

            return constructor.newInstance();

        } catch (InvocationTargetException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        } catch (InstantiationException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        } catch (IllegalAccessException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    }
    return null;
}

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  ww. java 2s  .  c o m*/
        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:org.apache.nifi.spring.SpringContextFactory.java

/**
 * Creates and instance of Spring Application Context scoped within a
 * dedicated Class Loader./*from   w w w .j  av  a 2s  .  c o  m*/
 * <br>
 * The core task of this factory is to load delegate that supports message
 * exchange with Spring Application Context ({@link SpringDataExchanger})
 * using the same class loader used to load the Application Context. Such
 * class loader isolation is required to ensure that multiple instances of
 * Application Context (representing different applications) and the
 * corresponding delegate can exist per single instance of Spring NAR.
 * <br>
 * The mechanism used here is relatively simple. While
 * {@link SpringDataExchanger} is available to the current class loader and
 * would normally be loaded once per instance of NAR, the below factory
 * method first obtains class bytes for {@link SpringDataExchanger} and then
 * loads it from these bytes via ClassLoader.defineClass(..) method, thus
 * ensuring that multiple instances of {@link SpringDataExchanger} class can
 * exist and everything that is loaded within its scope is using its class
 * loader. Upon exit, the class loader is destroyed via close method
 * essentially with everything that it loaded.
 * <br>
 * Also, during the initialization of {@link SpringDataExchanger} the new
 * class loader is set as Thread.contextClassLoader ensuring that if there
 * are any libraries used by Spring beans that rely on loading resources via
 * Thread.contextClassLoader can find such resources.
 */
static SpringDataExchanger createSpringContextDelegate(String classpath, String config) {
    List<URL> urls = gatherAdditionalClassPathUrls(classpath);
    SpringContextClassLoader contextCl = new SpringContextClassLoader(urls.toArray(new URL[] {}),
            SpringContextFactory.class.getClassLoader());
    ClassLoader tContextCl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(contextCl);
    try {
        InputStream delegateStream = contextCl
                .getResourceAsStream(SC_DELEGATE_NAME.replace('.', '/') + ".class");
        byte[] delegateBytes = IOUtils.toByteArray(delegateStream);
        Class<?> clazz = contextCl.doDefineClass(SC_DELEGATE_NAME, delegateBytes, 0, delegateBytes.length);
        Constructor<?> ctr = clazz.getDeclaredConstructor(String.class);
        ctr.setAccessible(true);
        SpringDataExchanger springDelegate = (SpringDataExchanger) ctr.newInstance(config);
        if (logger.isInfoEnabled()) {
            logger.info("Successfully instantiated Spring Application Context from '" + config + "'");
        }
        return springDelegate;
    } catch (Exception e) {
        try {
            contextCl.close();
        } catch (Exception e2) {
            // ignore
        }
        throw new IllegalStateException("Failed to instantiate Spring Application Context. Config path: '"
                + config + "'; Classpath: " + Arrays.asList(urls), e);
    } finally {
        Thread.currentThread().setContextClassLoader(tContextCl);
    }
}

From source file:com.android.tv.util.TestUtils.java

private static TvInputInfo createTvInputInfoForLmp(ResolveInfo service, String id, String parentId, int type)
        throws Exception {
    Constructor<TvInputInfo> constructor = TvInputInfo.class
            .getDeclaredConstructor(new Class[] { ResolveInfo.class, String.class, String.class, int.class });
    constructor.setAccessible(true);
    return constructor.newInstance(service, id, parentId, type);
}

From source file:com.android.tv.util.TestUtils.java

private static TvInputInfo createTvInputInfoForNpreview(ResolveInfo service, String id, String parentId,
        int type) throws Exception {
    Constructor<TvInputInfo> constructor = TvInputInfo.class
            .getDeclaredConstructor(new Class[] { ResolveInfo.class, String.class, String.class, int.class });
    constructor.setAccessible(true);
    return constructor.newInstance(service, id, parentId, type);
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Nullable/*from  w w w  .j  a  va2s.  c  o m*/
public static RemoteInput[] toCompat(@Nullable android.app.RemoteInput[] srcArray) {
    if (srcArray == null)
        return null;
    RemoteInput[] result = new RemoteInput[srcArray.length];
    try {
        Constructor constructor = RemoteInput.class.getDeclaredConstructor(String.class, CharSequence.class,
                CharSequence[].class, boolean.class, Bundle.class);
        constructor.setAccessible(true);
        for (int i = 0; i < srcArray.length; i++) {
            android.app.RemoteInput src = srcArray[i];
            result[i] = (RemoteInput) constructor.newInstance(src.getResultKey(), src.getLabel(),
                    src.getChoices(), src.getAllowFreeFormInput(), src.getExtras());
        }
    } catch (NoSuchMethodException | InvocationTargetException | InstantiationException
            | IllegalAccessException e) {
        Log.e(TAG, "Failed to create the remote inputs!");
        return null;
    }
    return result;
}

From source file:Main.java

/**
 * set constructor is accessible/*  www .j a v  a 2s.c o m*/
 * @param constructor {@link java.lang.reflect.Constructor}
 * @param <T> t
 */
public static <T> void makeAccessible(final Constructor<T> constructor) {
    if (!Modifier.isPublic(constructor.getModifiers())
            || !Modifier.isPublic(constructor.getDeclaringClass().getModifiers())) {
        constructor.setAccessible(true);
    }
}

From source file:com.android.tv.util.TestUtils.java

private static TvInputInfo createTvInputInfoForMnc(ResolveInfo service, String id, String parentId, int type,
        boolean isHardwareInput) throws Exception {
    Constructor<TvInputInfo> constructor = TvInputInfo.class.getDeclaredConstructor(
            new Class[] { ResolveInfo.class, String.class, String.class, int.class, boolean.class });
    constructor.setAccessible(true);
    return constructor.newInstance(service, id, parentId, type, isHardwareInput);
}

From source file:libepg.epg.section.SectionBodyTest.java

private static final SectionBody init(Object[] args) throws NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    SectionBody target;//  ww w .jav  a 2s. c  om
    Class<?>[] params = { TABLE_ID.class, byte[].class };
    Constructor<SectionBody> constructor = SectionBody.class.getDeclaredConstructor(params);
    constructor.setAccessible(true);
    target = constructor.newInstance(args);
    return target;
}