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.uimafit.spring.SpringContextResourceManager.java

/**
 * Instantiate a non-visible class.//from  w  ww . ja  v  a  2  s  .  c  om
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> T newInstance(String aClassName, Object... aArgs) throws ResourceInitializationException {
    Constructor constr = null;
    try {
        Class<?> cl = Class.forName(aClassName);

        List<Class> types = new ArrayList<Class>();
        List<Object> values = new ArrayList<Object>();
        for (int i = 0; i < aArgs.length; i += 2) {
            types.add((Class) aArgs[i]);
            values.add(aArgs[i + 1]);
        }

        constr = cl.getDeclaredConstructor(types.toArray(new Class[types.size()]));
        constr.setAccessible(true);
        return (T) constr.newInstance(values.toArray(new Object[values.size()]));
    } catch (Exception e) {
        throw new ResourceInitializationException(e);
    } finally {
        if (constr != null) {
            constr.setAccessible(false);
        }
    }
}

From source file:com.zc.util.refelect.Reflector.java

/**
 * ?constructorannotationClass/* w  w  w .ja  va2 s .  co m*/
 *
 * @param constructor
 *            constructor
 * @param annotationClass
 *            annotationClass
 *
 * @return {@link java.lang.annotation.Annotation}
 */
public static <T extends Annotation> T getAnnotation(Constructor constructor, Class annotationClass) {

    constructor.setAccessible(true);

    if (constructor.isAnnotationPresent(annotationClass)) {
        return (T) constructor.getAnnotation(annotationClass);
    }

    return null;
}

From source file:org.apache.tajo.storage.OldStorageManager.java

/**
 * Returns the proper Tablespace instance according to the dataFormat
 *
 * @param tajoConf Tajo system property.
 * @param uri Key that can identify each storage manager(may be a path)
 * @param dataFormat Storage type//from   w  ww. jav a  2  s .c  om
 * @return
 * @throws IOException
 */
public static synchronized Tablespace getStorageManager(TajoConf tajoConf, URI uri, String dataFormat)
        throws IOException {
    Preconditions.checkNotNull(tajoConf);
    Preconditions.checkNotNull(uri);
    Preconditions.checkNotNull(dataFormat);

    String typeName;
    if (dataFormat.equalsIgnoreCase("HBASE")) {
        typeName = "hbase";
    } else {
        typeName = "hdfs";
    }

    synchronized (storageManagers) {
        String storeKey = typeName + "_" + uri.toString();
        Tablespace manager = storageManagers.get(storeKey);

        if (manager == null) {
            Class<? extends Tablespace> storageManagerClass = tajoConf
                    .getClass(String.format("tajo.storage.manager.%s.class", typeName), null, Tablespace.class);

            if (storageManagerClass == null) {
                throw new IOException("Unknown Storage Type: " + typeName);
            }

            try {
                Constructor<? extends Tablespace> constructor = (Constructor<? extends Tablespace>) CONSTRUCTOR_CACHE
                        .get(storageManagerClass);
                if (constructor == null) {
                    constructor = storageManagerClass
                            .getDeclaredConstructor(TablespaceManager.TABLESPACE_PARAM);
                    constructor.setAccessible(true);
                    CONSTRUCTOR_CACHE.put(storageManagerClass, constructor);
                }
                manager = constructor.newInstance(new Object[] { "noname", uri, null });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            manager.init(tajoConf);
            storageManagers.put(storeKey, manager);
        }

        return manager;
    }
}

From source file:com.rockagen.commons.util.ClassUtil.java

/**
 * Create new instance of specified class and type
 * //from   ww w .  j  a va 2s.c om
 * @param clazz class
 * @param accessible accessible
 * @param parameterTypes parameter types
 * @param paramValue param value
 * @param <T> t
 * @return instance
 */
public static <T> T getInstance(Class<T> clazz, boolean accessible, Class<?>[] parameterTypes,
        Object[] paramValue) {
    if (clazz == null)
        return null;

    T t = null;

    try {
        if (parameterTypes != null && paramValue != null) {
            Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
            Object[] obj = new Object[parameterTypes.length];

            System.arraycopy(paramValue, 0, obj, 0, parameterTypes.length);
            constructor.setAccessible(accessible);
            t = constructor.newInstance(obj);
        }

    } catch (SecurityException e) {
        log.error("{}", e.getMessage(), e);
    } catch (NoSuchMethodException e) {
        log.error("{}", e.getMessage(), e);
    } catch (IllegalArgumentException e) {
        log.error("{}", e.getMessage(), e);
    } catch (InstantiationException e) {
        log.error("{}", e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.error("{}", e.getMessage(), e);
    } catch (InvocationTargetException e) {
        log.error("{}", e.getMessage(), e);
    }

    return t;
}

From source file:me.piebridge.android.preference.PreferenceFragment.java

@SuppressWarnings("unchecked")
public static <T> T callConstructor(Class<T> returnType, Class<?>[] parameterTypes, Object[] args) {
    try {/*  ww  w. jav  a2s .co m*/
        Constructor<?> constructor = returnType.getDeclaredConstructor(parameterTypes);
        constructor.setAccessible(true);
        return (T) constructor.newInstance(args);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (java.lang.InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:me.piebridge.android.preference.PreferenceFragment.java

/**
 * return XmlPullParser//from  w  w  w. j  ava2 s  . co m
 * @param xml compiled XML encoded in base64
 * @return XmlPullParser
 */
public static XmlPullParser getParser(String xml) {
    try {
        byte[] data = Base64.decode(xml, Base64.DEFAULT);

        // XmlBlock block = new XmlBlock(LAYOUT.getBytes("UTF-8"));
        Class<?> clazz = Class.forName("android.content.res.XmlBlock");
        Constructor<?> constructor = clazz.getDeclaredConstructor(byte[].class);
        constructor.setAccessible(true);
        Object block = constructor.newInstance(data);

        // XmlPullParser parser = block.newParser();
        Method method = clazz.getDeclaredMethod("newParser");
        method.setAccessible(true);
        return (XmlPullParser) method.invoke(block);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (java.lang.InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:cascading.util.Util.java

public static Object createProtectedObject(Class type, Object[] parameters, Class[] parameterTypes) {
    try {/*from  w w  w.j a v  a2  s.  com*/
        Constructor constructor = type.getDeclaredConstructor(parameterTypes);

        constructor.setAccessible(true);

        return constructor.newInstance(parameters);
    } catch (Exception exception) {
        exception.printStackTrace();

        throw new FlowException("unable to instantiate type: " + type.getName(), exception);
    }
}

From source file:org.apache.tajo.storage.TablespaceManager.java

private static Tablespace initializeTableSpace(String spaceName, URI uri, JSONObject spaceDesc) {
    final String scheme = UriUtil.getScheme(uri);
    Class<? extends Tablespace> clazz = TABLE_SPACE_HANDLERS.get(scheme);

    if (clazz == null) {
        throw new TajoRuntimeException(new UndefinedTablespaceHandlerException(scheme));
    }/*  w w w. ja  v  a 2  s .co m*/

    try {
        Constructor<? extends Tablespace> constructor = (Constructor<? extends Tablespace>) CONSTRUCTORS
                .get(clazz);

        if (constructor == null) {
            constructor = clazz.getDeclaredConstructor(TABLESPACE_PARAM);
            constructor.setAccessible(true);
            CONSTRUCTORS.put(clazz, constructor);
        }

        return constructor.newInstance(new Object[] { spaceName, uri, spaceDesc });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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   w w  w  . jav a2  s.c o  m*/
 *         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:com.llkj.cm.restfull.network.NetworkConnection.java

/**
 * By default the user agent is empty. If you want to use the standard Android user agent, call this method before using the
 * <code>retrieveResponseFromService</code> methods
 * //  w ww . ja  v a2  s .  c  o  m
 * @param context The context
 */
public static void generateDefaultUserAgent(final Context context) {
    if (sDefaultUserAgent != null) {
        return;
    }

    try {
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(context, null);
            sDefaultUserAgent = settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        if (Thread.currentThread().getName().equalsIgnoreCase("main")) {
            WebView webview = new WebView(context);
            sDefaultUserAgent = webview.getSettings().getUserAgentString();
        } else {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    WebView webview = new WebView(context);
                    sDefaultUserAgent = webview.getSettings().getUserAgentString();
                    Looper.loop();
                }
            };
            thread.start();
        }
    }
}