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.hama.util.ReflectionUtils.java

@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> theClass) {
    Preconditions.checkNotNull(theClass);
    T result;//from   www .jav a2 s  .com
    try {
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
        if (null == meth) {
            meth = theClass.getDeclaredConstructor(new Class[0]);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.openehealth.ipf.commons.lbs.utils.NiceClass.java

/**
 * Ensures that a constructors of a class is null safe.
 * @param obj/*from www.  j a  v  a  2  s  . c  om*/
 *          object to test
 * @param args
 *          dummy arguments of all different parameter types that the constructor has
 * @param optional
 *          optional dummy arguments that can also be set to {@code null} without breaking
 *          null-safety
 * @throws any thrown exception that were not expected. Never an {@link IllegalArgumentException}.
 */
public static void checkConstructorIsNullSafe(Constructor<?> constructor, List<?> args, List<?> optional)
        throws Exception {
    log.info("checked " + constructor);

    constructor.setAccessible(true);

    Class<?>[] parameterTypes = constructor.getParameterTypes();
    Object[] parameterValues = getParameterValues(parameterTypes, args);

    for (int idx = 0; idx < parameterValues.length; ++idx) {
        if (!isOptional(constructor.getName(), idx, optional, parameterValues[idx])) {
            Object[] parameterValuesWithNull = Arrays.copyOf(parameterValues, parameterValues.length);
            parameterValuesWithNull[idx] = null;

            try {
                constructor.newInstance(parameterValuesWithNull);
                fail("Should throw an " + IllegalArgumentException.class.getSimpleName());
            } catch (InvocationTargetException e) {
                assertEquals(IllegalArgumentException.class, e.getCause().getClass());
            }
        }
    }
}

From source file:appeng.client.render.model.UVLModelLoader.java

private static Object deserializer(Class clas) {
    try {/*from w ww  .j av  a2  s. co  m*/
        clas = Class.forName(clas.getName() + "$Deserializer");
        Constructor constr = clas.getDeclaredConstructor();
        constr.setAccessible(true);
        return constr.newInstance();
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.dwdesign.tweetings.util.WebViewProxySettings.java

public static boolean setProxy(WebView webView, String host, int port) {
    final Context context = webView.getContext();
    // PSIPHON: added support for Android 4.x WebView proxy
    try {//w  w w. j  av a 2 s. co m
        final Class<?> webViewCoreClass = Class.forName("android.webkit.WebViewCore");
        final Class<?> proxyPropertiesClass = Class.forName("android.net.ProxyProperties");
        if (webViewCoreClass != null && proxyPropertiesClass != null) {
            final Method m = webViewCoreClass.getDeclaredMethod("sendStaticMessage", Integer.TYPE,
                    Object.class);
            final Constructor<?> c = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE,
                    String.class);

            if (m != null && c != null) {
                m.setAccessible(true);
                c.setAccessible(true);
                final Object properties = c.newInstance(host, port, null);

                // android.webkit.WebViewCore.EventHub.PROXY_CHANGED = 193;
                m.invoke(null, 193, properties);
                return true;
            }
        }
    } catch (final Exception e) {
        Log.e("ProxySettings",
                "Exception setting WebKit proxy through android.net.ProxyProperties: " + e.toString());
    }

    try {
        final Object requestQueueObject = getRequestQueue(context);
        if (requestQueueObject != null) {
            // Create Proxy config object and set it into request Q
            final HttpHost httpHost = new HttpHost(host, port, "http");
            setDeclaredField(requestQueueObject, "mProxyHost", httpHost);
            // Log.d("Webkit Setted Proxy to: " + host + ":" + port);
            return true;
        }
    } catch (final Exception e) {
        Log.e("ProxySettings",
                "Exception setting WebKit proxy through android.webkit.Network: " + e.toString());
    }

    return false;
}

From source file:com.github.jinahya.codec.commons.AbstractEncoderProxy.java

/**
 * Creates a new proxy instance.// w w  w  . j av a 2 s .  c  om
 *
 * @param <P> proxy type parameter
 * @param <T> encoder type parameter
 * @param loader class loader
 * @param interfaces interfaces
 * @param proxyType proxy type
 * @param encoderType encoder type
 * @param encoder encoder
 *
 * @return a new proxy instance.
 */
protected static <P extends AbstractEncoderProxy<T>, T> Object newInstance(final ClassLoader loader,
        final Class<?>[] interfaces, final Class<P> proxyType, final Class<T> encoderType, final T encoder) {

    if (loader == null) {
        throw new NullPointerException("loader");
    }

    if (interfaces == null) {
        throw new NullPointerException("interfaces");
    }

    if (proxyType == null) {
        throw new NullPointerException("proxyType");
    }

    if (encoderType == null) {
        throw new NullPointerException("encoderType");
    }

    if (encoder == null) {
        //throw new NullPointerException("encoder");
    }

    try {
        final Constructor<P> constructor = proxyType.getDeclaredConstructor(encoderType);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return Proxy.newProxyInstance(loader, interfaces, constructor.newInstance(encoder));
        } catch (final IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (final InstantiationException ie) {
            throw new RuntimeException(ie);
        } catch (final InvocationTargetException ite) {
            throw new RuntimeException(ite);
        }
    } catch (final NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}

From source file:com.codelanx.codelanxlib.util.exception.Exceptions.java

/**
 * Dynamically constructs a new instance of a {@link RuntimeException}
 * either via a {@link RuntimeException#RuntimeException(String)}
 * constructor or a no-argument constructor
 *
 * @since 0.1.0//  w  w w .  java2 s.c o m
 * @version 0.1.0
 *
 * @param <T> The {@link RuntimeException} type
 * @param ex The exception class to instantiate
 * @param message The message to add, {@code null} if there is no message
 * @return The newly constructed {@link RuntimeException}
 */
private static <T extends RuntimeException> T newException(Class<T> ex, String message) {
    if (message != null) {
        try {
            Constructor<T> c = ex.getConstructor(String.class);
            c.setAccessible(true);
            return c.newInstance(message);
        } catch (NoSuchMethodException e) {
            Debugger.print(Level.WARNING, String.format(
                    "Class '%s' does not have a String " + "message constructor! Using default constructor...",
                    ex.getName()));
        } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            Debugger.error(e, "Error creating new exception instance");
        }
    }
    //Now try here if the previous failed or message wasn't null
    try {
        return ex.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        Debugger.error(e, "Error creating new exception instance");
    }
    throw new IllegalArgumentException(String.format(
            "Class '%s' does not have the " + "appropriate constructors to be instantiated", ex.getName()));
}

From source file:com.github.jinahya.codec.commons.AbstractDecoderProxy.java

/**
 * Creates a new proxy instance./*ww w . jav a  2s.  c  o m*/
 *
 * @param <P> proxy type parameter
 * @param <T> decoder type parameter
 * @param loader class loader
 * @param interfaces interfaces
 * @param proxyType proxy type
 * @param decoderType decoder type
 * @param decoder decoder
 *
 * @return a new proxy instance.
 */
protected static <P extends AbstractDecoderProxy<T>, T> Object newInstance(final ClassLoader loader,
        final Class<?>[] interfaces, final Class<P> proxyType, final Class<T> decoderType, final T decoder) {

    if (loader == null) {
        throw new NullPointerException("loader");
    }

    if (interfaces == null) {
        throw new NullPointerException("interfaces");
    }

    if (proxyType == null) {
        throw new NullPointerException("proxyType");
    }

    if (decoderType == null) {
        throw new NullPointerException("decoderType");
    }

    if (decoder == null) {
        //throw new NullPointerException("decoder");
    }

    try {
        final Constructor<P> constructor = proxyType.getDeclaredConstructor(decoderType);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return Proxy.newProxyInstance(loader, interfaces, constructor.newInstance(decoder));
        } catch (final InstantiationException ie) {
            throw new RuntimeException(ie);
        } catch (final IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (final InvocationTargetException ite) {
            throw new RuntimeException(ite);
        }
    } catch (final NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}

From source file:org.apache.drill.exec.store.hive.HiveSubScan.java

public static InputSplit deserializeInputSplit(String base64, String className)
        throws IOException, ReflectiveOperationException {
    Constructor<?> constructor = Class.forName(className).getDeclaredConstructor();
    if (constructor == null) {
        throw new ReflectiveOperationException(
                "Class " + className + " does not implement a default constructor.");
    }//from   w  ww. ja v a  2s  .  c o m
    constructor.setAccessible(true);
    InputSplit split = (InputSplit) constructor.newInstance();
    ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(Base64.decodeBase64(base64));
    split.readFields(byteArrayDataInput);
    return split;
}

From source file:org.talend.core.utils.ReflectionUtils.java

/**
 * DOC ycbai Comment method "newInstance".
 * //from   ww w .  jav  a  2 s  . com
 * Create a new instance of a class.
 * 
 * @param className
 * @param initialize
 * @param loader
 * @param args
 * @return
 * @throws ClassNotFoundException
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws IllegalArgumentException
 */
public static Object newInstance(String className, ClassLoader loader, Object[] args, Class... argTypes)
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Object instance = null;
    Class newClass = null;
    if (loader != null) {
        newClass = Class.forName(className, true, loader);
    } else {
        newClass = Class.forName(className);
    }
    Class[] argsClass = new Class[args.length];
    if (argTypes.length > 0 && argTypes.length == args.length) {
        argsClass = argTypes;
    } else {
        for (int i = 0, j = args.length; i < j; i++) {
            argsClass[i] = args[i].getClass();
        }
    }
    Constructor cons = newClass.getDeclaredConstructor(argsClass);
    cons.setAccessible(true);
    instance = cons.newInstance(args);

    return instance;
}

From source file:ca.psiphon.tunneledwebview.WebViewProxySettings.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@SuppressWarnings("rawtypes")
private static boolean setWebkitProxyKitKat(Context appContext, String host, int port) {
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", port + "");
    System.setProperty("https.proxyHost", host);
    System.setProperty("https.proxyPort", port + "");
    try {/*from   w  w  w.  ja va  2  s . co  m*/
        Class applicationClass = Class.forName("android.app.Application");
        Field loadedApkField = applicationClass.getDeclaredField("mLoadedApk");
        loadedApkField.setAccessible(true);
        Object loadedApk = loadedApkField.get(appContext);
        Class loadedApkClass = Class.forName("android.app.LoadedApk");
        Field receiversField = loadedApkClass.getDeclaredField("mReceivers");
        receiversField.setAccessible(true);
        ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object receiver : ((ArrayMap) receiverMap).keySet()) {
                Class receiverClass = receiver.getClass();
                if (receiverClass.getName().contains("ProxyChangeListener")) {
                    Method onReceiveMethod = receiverClass.getDeclaredMethod("onReceive", Context.class,
                            Intent.class);
                    Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);

                    final String CLASS_NAME = "android.net.ProxyProperties";
                    Class proxyPropertiesClass = Class.forName(CLASS_NAME);
                    Constructor constructor = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE,
                            String.class);
                    constructor.setAccessible(true);
                    Object proxyProperties = constructor.newInstance(host, port, null);
                    intent.putExtra("proxy", (Parcelable) proxyProperties);

                    onReceiveMethod.invoke(receiver, appContext, intent);
                }
            }
        }
        return true;
    } catch (ClassNotFoundException e) {
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {
    } catch (IllegalArgumentException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (InstantiationException e) {
    }
    return false;
}