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:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java

/**
 * //from   ww  w  . java  2  s. co m
 */
public static JRSaxParserFactory getFactory(JasperReportsContext jasperReportsContext, String className) {
    JRSaxParserFactory factory = null;
    try {
        @SuppressWarnings("unchecked")
        Class<? extends JRSaxParserFactory> clazz = (Class<? extends JRSaxParserFactory>) JRClassLoader
                .loadClassForName(className);
        if (!JRSaxParserFactory.class.isAssignableFrom(clazz)) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_INCOMPATIBLE_CLASS,
                    new Object[] { className, JRSaxParserFactory.class.getName() });
        }

        try {
            Constructor<? extends JRSaxParserFactory> constr = clazz
                    .getConstructor(new Class[] { JasperReportsContext.class });
            factory = constr.newInstance(jasperReportsContext);
        } catch (NoSuchMethodException | InvocationTargetException e) {
            //ignore
        }

        if (factory == null) {
            factory = clazz.getDeclaredConstructor().newInstance();
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
            | InvocationTargetException e) {
        throw new JRRuntimeException(e);
    }

    return factory;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules://w  w  w .  j av  a  2  s.  co m
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.bt.download.android.gui.UniversalScanner.java

private static Uri nativeScanFile(Context context, String path) {
    try {/*from  ww  w.j  a  v  a 2s  . c  o  m*/
        File f = new File(path);

        Class<?> clazz = Class.forName("android.media.MediaScanner");

        Constructor<?> mediaScannerC = clazz.getDeclaredConstructor(Context.class);
        Object scanner = mediaScannerC.newInstance(context);

        Field mClientF = clazz.getDeclaredField("mClient");
        mClientF.setAccessible(true);
        Object mClient = mClientF.get(scanner);

        Method scanSingleFileM = clazz.getDeclaredMethod("scanSingleFile", String.class, String.class,
                String.class);
        Uri fileUri = (Uri) scanSingleFileM.invoke(scanner, f.getAbsolutePath(), "external", "data/raw");
        int n = context.getContentResolver().delete(fileUri, null, null);
        if (n > 0) {
            LOG.debug("Deleted from Files provider: " + fileUri);
        }

        Field mNoMediaF = mClient.getClass().getDeclaredField("mNoMedia");
        mNoMediaF.setAccessible(true);
        mNoMediaF.setBoolean(mClient, false);

        // This is only for HTC (tested only on HTC One M8)
        try {
            Field mFileCacheF = clazz.getDeclaredField("mFileCache");
            mFileCacheF.setAccessible(true);
            mFileCacheF.set(scanner, new HashMap<String, Object>());
        } catch (Throwable e) {
            // no an HTC, I need some time to refactor this hack
        }

        Method doScanFileM = mClient.getClass().getDeclaredMethod("doScanFile", String.class, String.class,
                long.class, long.class, boolean.class, boolean.class, boolean.class);
        Uri mediaUri = (Uri) doScanFileM.invoke(mClient, f.getAbsolutePath(), null, f.lastModified(),
                f.length(), false, true, false);

        Method releaseM = clazz.getDeclaredMethod("release");
        releaseM.invoke(scanner);

        return mediaUri;

    } catch (Throwable e) {
        e.printStackTrace();
        return null;
    }
}

From source file:TypeUtil.java

/** Convert String value to instance.
 * @param type The class of the instance, which may be a primitive TYPE field.
 * @param value The value as a string./* w ww  .  j  ava 2s.  c  o m*/
 * @return The value as an Object.
 */
public static Object valueOf(Class type, String value) {
    try {
        if (type.equals(java.lang.String.class))
            return value;

        Method m = (Method) class2Value.get(type);
        if (m != null)
            return m.invoke(null, new Object[] { value });

        if (type.equals(java.lang.Character.TYPE) || type.equals(java.lang.Character.class))
            return new Character(value.charAt(0));

        Constructor c = type.getConstructor(stringArg);
        return c.newInstance(new Object[] { value });
    }

    catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof Error)
            throw (Error) (e.getTargetException());

    }
    return null;
}

From source file:Main.java

public static Object getNewObject(Class<?> outerClass, String innerClassName, Class<?> parameterTypes[],
        Object parameters[]) throws Exception {
    // Get all inner classes
    Class<?> innerClasses[] = outerClass.getDeclaredClasses();
    // find the inner class that matches the order
    Constructor<?> constructor = null;
    for (int index = 0; index < innerClasses.length; index++) {
        if (innerClassName.equals(innerClasses[index].getSimpleName())) {
            constructor = innerClasses[index].getConstructor(parameterTypes);
        }/* w w  w.ja va 2 s .c  o m*/
    }
    if (constructor != null) {
        constructor.setAccessible(true);
        Object obj = constructor.newInstance(parameters);
        return obj;
    }
    return null;
}

From source file:com.mh.commons.utils.Reflections.java

/**
 * //from w  w  w.  j  ava2s.  c om
 * @param className
 * @param args
 * @return
 * @throws ClassNotFoundException
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public static Object newInstance(String className, Object[] args)
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Class newoneClass = Class.forName(className);
    Class[] argsClass = new Class[args.length];
    for (int i = 0, j = args.length; i < j; i++) {
        argsClass[i] = args[i].getClass();
    }
    Constructor cons = newoneClass.getConstructor(argsClass);
    return cons.newInstance(args);
}

From source file:dk.itst.oiosaml.sp.service.util.Utils.java

public static Map<String, SAMLHandler> getHandlers(Configuration config, ServletContext servletContext) {
    Map<String, SAMLHandler> handlers = new HashMap<String, SAMLHandler>();

    for (Iterator<?> i = config.getKeys(); i.hasNext();) {
        String key = (String) i.next();
        if (!key.startsWith("oiosaml-sp.protocol.endpoints."))
            continue;
        log.debug("Checking " + key);

        try {/*from w  ww .java2 s  .c om*/
            Class<?> c = Class.forName(config.getString(key));
            SAMLHandler instance;
            try {
                Constructor<?> constructor = c.getConstructor(Configuration.class);
                instance = (SAMLHandler) constructor.newInstance(config);
            } catch (NoSuchMethodException e) {
                try {
                    Constructor<?> constructor = c.getConstructor(ServletContext.class);
                    instance = (SAMLHandler) constructor.newInstance(servletContext);
                } catch (NoSuchMethodException ex) {
                    instance = (SAMLHandler) c.newInstance();
                }
            }

            //            log.info("instance:" + instance.toString()); // pdurbin
            handlers.put(key.substring(key.lastIndexOf('.') + 1), instance);

        } catch (Exception e) {
            log.error("Unable to instantiate " + key + ": " + config.getString(key), e);
            throw new RuntimeException(e);
        }

    }

    return handlers;
}

From source file:com.revolsys.util.JavaBeanUtil.java

public static <T> T invokeConstructor(final Constructor<? extends T> constructor, final Object... args) {
    try {/* www .  ja  v  a  2s. c  om*/
        final T object = constructor.newInstance(args);
        return object;
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Error e) {
        throw e;
    } catch (final InvocationTargetException e) {
        final Throwable t = e.getTargetException();
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new RuntimeException(t.getMessage(), t);
        }
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jfree.data.time.RegularTimePeriod.java

/**
 * Creates a time period that includes the specified millisecond, assuming
 * the given time zone.//from  w w w. j  ava  2s . c o  m
 *
 * @param c  the time period class.
 * @param millisecond  the time.
 * @param zone  the time zone.
 * @param locale  the locale.
 *
 * @return The time period.
 */
public static RegularTimePeriod createInstance(Class c, Date millisecond, TimeZone zone, Locale locale) {
    RegularTimePeriod result = null;
    try {
        Constructor constructor = c
                .getDeclaredConstructor(new Class[] { Date.class, TimeZone.class, Locale.class });
        result = (RegularTimePeriod) constructor.newInstance(new Object[] { millisecond, zone, locale });
    } catch (Exception e) {
        // do nothing, so null is returned
    }
    return result;
}

From source file:hivemall.xgboost.XGBoostUDTF.java

@Nonnull
private static Booster createXGBooster(final Map<String, Object> params, final List<LabeledPoint> input)
        throws NoSuchMethodException, XGBoostError, IllegalAccessException, InvocationTargetException,
        InstantiationException {/*from w w w  .  j  a  v a 2s . co m*/
    Class<?>[] args = { Map.class, DMatrix[].class };
    Constructor<Booster> ctor = Booster.class.getDeclaredConstructor(args);
    ctor.setAccessible(true);
    return ctor.newInstance(new Object[] { params, new DMatrix[] { new DMatrix(input.iterator(), "") } });
}