Example usage for java.lang.reflect Constructor newInstance

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException 

Source Link

Document

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

Usage

From source file:com.microsoft.tfs.core.internal.wrappers.WrapperUtils.java

/**
 * <p>/*from w  w w  . j  a  v  a  2  s.c o  m*/
 * Takes an array of web service objects (for example, an array of
 * {@link _Item}) and returns an array of web service wrapper objects of the
 * given type (for instance, {@link Item}).
 * </p>
 * <p>
 * A constructor for the given wrapper type that accepts one of the given
 * service objects must exist.
 * </p>
 * <p>
 * <code>null</code> values in the web service objects are copied into the
 * returned array.
 * </p>
 *
 * @param wrapperType
 *        the wrapper object class name (not array class) to use (must not
 *        be <code>null</code>)
 * @param webServiceObjects
 *        the objects to wrap (if null, null is returned)
 * @return a new array of wrapper objects, where each wraps one of the given
 *         web service objects
 */
public static Object wrap(final Class wrapperType, final Object[] webServiceObjects) {
    Check.notNull(wrapperType, "wrapperType"); //$NON-NLS-1$

    if (webServiceObjects == null) {
        return null;
    }

    final Object ret = Array.newInstance(wrapperType, webServiceObjects.length);
    Class webServiceObjectType = null;
    Constructor constructor = null;

    if (webServiceObjects.length > 0) {
        try {

            for (int i = 0; i < webServiceObjects.length; i++) {
                if (constructor == null && webServiceObjects[i] != null) {
                    webServiceObjectType = webServiceObjects[i].getClass();
                    constructor = wrapperType.getConstructor(new Class[] { webServiceObjectType });
                }

                /*
                 * Persist null values.
                 */
                Array.set(ret, i,
                        (webServiceObjects[i] != null)
                                ? constructor.newInstance(new Object[] { webServiceObjects[i] })
                                : null);
            }

        } catch (final NoSuchMethodException e) {
            final String message = MessageFormat.format(
                    "Wrapper error: the desired wrapper class {0} does not have a visible constructor that accepts the web service type {1}", //$NON-NLS-1$
                    wrapperType, webServiceObjectType);

            log.error(message, e);
            throw new RuntimeException(message);
        } catch (final Exception e) {
            final String message = MessageFormat.format("Error wrapping {0} in {1}", //$NON-NLS-1$
                    webServiceObjectType, wrapperType);

            log.error(message, e);
            throw new RuntimeException(message, e);
        }
    }

    return ret;
}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;//from ww  w  .  j ava2  s.  com
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (!replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof org.hibernate.collection.PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((org.hibernate.collection.PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("com.ppp")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:cascading.flow.hadoop.util.HadoopUtil.java

protected static <C extends Configuration> C callCopyConstructor(Class type, Configuration parent) {
    try {/*www.  j ava  2 s  . c o m*/
        Constructor<C> constructor = type.getConstructor(parent.getClass());

        return constructor.newInstance(parent);
    } catch (NoSuchMethodException | InvocationTargetException | InstantiationException
            | IllegalAccessException exception) {
        throw new CascadingException("unable to create copy of: " + type);
    }
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Get the reconnection policy.//from   w w  w.j av a 2 s. co m
 */
public static ReconnectionPolicy getReconnectionPolicy(String rcString, String parameters)
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    ReconnectionPolicy policy = null;
    //ReconnectionPolicy childPolicy = null;
    if (!rcString.contains(".")) {
        rcString = "com.datastax.driver.core.policies." + rcString;
    }

    if (parameters.length() > 0) {
        // Child policy or parameters have been specified
        String paramsRegex = "([^,]+\\(.+?\\))|([^,]+)";
        Pattern param_pattern = Pattern.compile(paramsRegex);
        Matcher lb_matcher = param_pattern.matcher(parameters);

        ArrayList<Object> paramList = Lists.newArrayList();
        ArrayList<Class> primaryParametersClasses = Lists.newArrayList();
        int nb = 0;
        while (lb_matcher.find()) {
            if (lb_matcher.groupCount() > 0) {
                try {
                    if (lb_matcher.group().contains("(") && !lb_matcher.group().trim().startsWith("(")) {
                        // We are dealing with child policies here
                        primaryParametersClasses.add(LoadBalancingPolicy.class);
                        // Parse and add child policy to the parameter list
                        paramList.add(parseReconnectionPolicy(lb_matcher.group()));
                        nb++;
                    } else {
                        // We are dealing with parameters that are not policies here
                        String param = lb_matcher.group();
                        if (param.contains("'") || param.contains("\"")) {
                            primaryParametersClasses.add(String.class);
                            paramList.add(new String(param.trim().replace("'", "").replace("\"", "")));
                        } else if (param.contains(".") || param.toLowerCase().contains("(double)")
                                || param.toLowerCase().contains("(float)")) {
                            // gotta allow using float or double
                            if (param.toLowerCase().contains("(double)")) {
                                primaryParametersClasses.add(double.class);
                                paramList.add(Double.parseDouble(param.replace("(double)", "").trim()));
                            } else {
                                primaryParametersClasses.add(float.class);
                                paramList.add(Float.parseFloat(param.replace("(float)", "").trim()));
                            }
                        } else {
                            if (param.toLowerCase().contains("(long)")) {
                                primaryParametersClasses.add(long.class);
                                paramList.add(Long.parseLong(param.toLowerCase().replace("(long)", "").trim()));
                            } else {
                                primaryParametersClasses.add(int.class);
                                paramList
                                        .add(Integer.parseInt(param.toLowerCase().replace("(int)", "").trim()));
                            }
                        }
                        nb++;
                    }
                } catch (Exception e) {
                    log.error("Could not parse the Cassandra reconnection policy! " + e.getMessage());
                }
            }
        }

        if (nb > 0) {
            // Instantiate load balancing policy with parameters
            Class<?> clazz = Class.forName(rcString);
            Constructor<?> constructor = clazz.getConstructor(
                    primaryParametersClasses.toArray(new Class[primaryParametersClasses.size()]));

            return (ReconnectionPolicy) constructor
                    .newInstance(paramList.toArray(new Object[paramList.size()]));
        }
        // Only one policy has been specified, with no parameter or child policy
        Class<?> clazz = Class.forName(rcString);
        policy = (ReconnectionPolicy) clazz.newInstance();
        return policy;
    }
    Class<?> clazz = Class.forName(rcString);
    policy = (ReconnectionPolicy) clazz.newInstance();
    return policy;
}

From source file:ch.flashcard.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields,
        Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth,
        SerializationType serializationType) throws Exception {

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;//  ww  w  .  jav  a2  s .  c  o  m
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (replacement != null && !replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:com.buaa.cfs.utils.NetUtils.java

@SuppressWarnings("unchecked")
private static <T extends IOException> T wrapWithMessage(T exception, String msg) {
    Class<? extends Throwable> clazz = exception.getClass();
    try {/*from ww  w  .  j  a v a2  s  . c o  m*/
        Constructor<? extends Throwable> ctor = clazz.getConstructor(String.class);
        Throwable t = ctor.newInstance(msg);
        return (T) (t.initCause(exception));
    } catch (Throwable e) {
        LOG.warn("Unable to wrap exception of type " + clazz + ": it has no (String) constructor", e);
        return exception;
    }
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Get the load balancing policy.//from   ww w . ja v  a 2  s. c  o  m
 */
public static LoadBalancingPolicy getLbPolicy(String lbString, String parameters)
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    LoadBalancingPolicy policy = null;
    if (!lbString.contains(".")) {
        lbString = "com.datastax.driver.core.policies." + lbString;
    }

    if (parameters.length() > 0) {
        // Child policy or parameters have been specified
        String paramsRegex = "([^,]+\\(.+?\\))|([^,]+)";
        Pattern param_pattern = Pattern.compile(paramsRegex);
        Matcher lb_matcher = param_pattern.matcher(parameters);

        ArrayList<Object> paramList = Lists.newArrayList();
        ArrayList<Class> primaryParametersClasses = Lists.newArrayList();
        int nb = 0;
        while (lb_matcher.find()) {
            if (lb_matcher.groupCount() > 0) {
                try {
                    if (lb_matcher.group().contains("(") && !lb_matcher.group().trim().startsWith("(")) {
                        // We are dealing with child policies here
                        primaryParametersClasses.add(LoadBalancingPolicy.class);
                        // Parse and add child policy to the parameter list
                        paramList.add(parseLbPolicy(lb_matcher.group()));
                        nb++;
                    } else {
                        // We are dealing with parameters that are not policies here
                        String param = lb_matcher.group();
                        if (param.contains("'") || param.contains("\"")) {
                            primaryParametersClasses.add(String.class);
                            paramList.add(new String(param.trim().replace("'", "").replace("\"", "")));
                        } else if (param.contains(".") || param.toLowerCase().contains("(double)")
                                || param.toLowerCase().contains("(float)")) {
                            // gotta allow using float or double
                            if (param.toLowerCase().contains("(double)")) {
                                primaryParametersClasses.add(double.class);
                                paramList.add(Double.parseDouble(param.replace("(double)", "").trim()));
                            } else {
                                primaryParametersClasses.add(float.class);
                                paramList.add(Float.parseFloat(param.replace("(float)", "").trim()));
                            }
                        } else {
                            if (param.toLowerCase().contains("(long)")) {
                                primaryParametersClasses.add(long.class);
                                paramList.add(Long.parseLong(param.toLowerCase().replace("(long)", "").trim()));
                            } else {
                                primaryParametersClasses.add(int.class);
                                paramList
                                        .add(Integer.parseInt(param.toLowerCase().replace("(int)", "").trim()));
                            }
                        }
                        nb++;
                    }
                } catch (Exception e) {
                    log.error("Could not parse the Cassandra load balancing policy! " + e.getMessage());
                }
            }
        }
        if (nb > 0) {
            // Instantiate load balancing policy with parameters
            if (lbString.toLowerCase().contains("latencyawarepolicy")) {
                //special sauce for the latency aware policy which uses a builder subclass to instantiate
                Builder builder = LatencyAwarePolicy.builder((LoadBalancingPolicy) paramList.get(0));

                builder.withExclusionThreshold((Double) paramList.get(1));
                builder.withScale((Long) paramList.get(2), TimeUnit.MILLISECONDS);
                builder.withRetryPeriod((Long) paramList.get(3), TimeUnit.MILLISECONDS);
                builder.withUpdateRate((Long) paramList.get(4), TimeUnit.MILLISECONDS);
                builder.withMininumMeasurements((Integer) paramList.get(5));

                return builder.build();

            } else {
                Class<?> clazz = Class.forName(lbString);
                Constructor<?> constructor = clazz.getConstructor(
                        primaryParametersClasses.toArray(new Class[primaryParametersClasses.size()]));

                return (LoadBalancingPolicy) constructor
                        .newInstance(paramList.toArray(new Object[paramList.size()]));
            }
        } else {
            // Only one policy has been specified, with no parameter or child policy
            Class<?> clazz = Class.forName(lbString);
            policy = (LoadBalancingPolicy) clazz.newInstance();
            return policy;
        }
    } else {
        // Only one policy has been specified, with no parameter or child policy
        Class<?> clazz = Class.forName(lbString);
        policy = (LoadBalancingPolicy) clazz.newInstance();
        return policy;
    }
}

From source file:eu.stratosphere.nephele.io.compression.CompressionLoader.java

@SuppressWarnings("unchecked")
private static CompressionLibrary initCompressionLibrary(String libraryClass) {

    Class<? extends CompressionLibrary> compressionLibraryClass;
    try {/*from   ww  w  .j av a 2 s.  c  o  m*/
        compressionLibraryClass = (Class<? extends CompressionLibrary>) Class.forName(libraryClass);
    } catch (ClassNotFoundException e1) {
        LOG.error(e1);
        return null;
    }

    if (compressionLibraryClass == null) {
        LOG.error("Cannot load compression library " + libraryClass);
        return null;
    }

    Constructor<? extends CompressionLibrary> constructor;
    try {
        constructor = compressionLibraryClass.getConstructor(String.class);
    } catch (SecurityException e) {
        LOG.error(e);
        return null;
    } catch (NoSuchMethodException e) {
        LOG.error(e);
        return null;
    }
    if (constructor == null) {
        LOG.error("Cannot find matching constructor for class " + compressionLibraryClass.toString());
        return null;
    }

    CompressionLibrary compressionLibrary;

    try {
        compressionLibrary = constructor.newInstance(getNativeLibraryPath(libraryClass));
    } catch (IllegalArgumentException e) {
        LOG.error(StringUtils.stringifyException(e));
        return null;
    } catch (InstantiationException e) {
        LOG.error(StringUtils.stringifyException(e));
        return null;
    } catch (IllegalAccessException e) {
        LOG.error(StringUtils.stringifyException(e));
        return null;
    } catch (InvocationTargetException e) {
        LOG.error(StringUtils.stringifyException(e));
        return null;
    }

    return compressionLibrary;
}

From source file:com.appleframework.jmx.core.services.MBeanServiceImpl.java

public static Object getTypedValue(ApplicationConfig appConfig, String value, String type) {

    if (type.equals("int")) {
        type = "java.lang.Integer";
    } else if (type.equals("long")) {
        type = "java.lang.Long";
    } else if (type.equals("short")) {
        type = "java.lang.Short";
    } else if (type.equals("float")) {
        type = "java.lang.Float";
    } else if (type.equals("double")) {
        type = "java.lang.Double";
    } else if (type.equals("char")) {
        type = "java.lang.Character";
    } else if (type.equals("boolean")) {
        type = "java.lang.Boolean";
    } else if (type.equals("byte")) {
        type = "java.lang.Byte";
    }/*  ww w  .  ja v a  2 s.c o  m*/

    try {
        /* handle ObjectName as a special type */
        if (type.equals("javax.management.ObjectName")) {
            Class<?> clazz = Class.forName(type, true, appConfig.getApplicationClassLoader());
            try {
                Constructor<?> ctor = clazz.getConstructor(new Class[] { String.class });
                return ctor.newInstance(new Object[] { value });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        /* other types */
        return ConvertUtils.convert(value, Class.forName(type));
    } catch (ClassNotFoundException 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  ww  w .  j a va  2s  .  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;
}