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:fi.luontola.cqrshotel.JsonSerializationTest.java

private static Object newDummy(Class<?> type) throws Exception {
    Constructor<?> ctor = type.getConstructors()[0];
    Class<?>[] paramTypes = ctor.getParameterTypes();
    Object[] params = new Object[paramTypes.length];
    for (int i = 0; i < paramTypes.length; i++) {
        params[i] = randomValue(paramTypes[i]);
    }//from  w w w  .  java  2s  .co  m
    return ctor.newInstance(params);
}

From source file:com.dianping.squirrel.client.util.ClassUtils.java

/**
 * construct instance violently//from w  w  w  . j  av  a 2  s .c o m
 * 
 * @param <T>
 * @param clazz
 * @param parameters
 * @return
 */
public static <T> T newInstance(Class<T> clazz, Object... parameters) {
    try {
        if (parameters == null) {
            parameters = new Object[0];
        }
        int paramLen = parameters.length;
        Class<?>[] parameterTypes = new Class<?>[paramLen];
        for (int i = 0; i < paramLen; i++) {
            parameterTypes[i] = parameters[i].getClass();
        }
        Constructor<T> constructor = getMatchingDeclaredConstructor(clazz, parameterTypes);
        boolean accessible = constructor.isAccessible();
        if (accessible) {
            return constructor.newInstance(parameters);
        } else {
            synchronized (constructor) {
                try {
                    constructor.setAccessible(true);
                    return constructor.newInstance(parameters);
                } finally {
                    constructor.setAccessible(accessible);
                }
            }
        }
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    throw new IllegalStateException("Should never get here");
}

From source file:com.flozano.socialauth.AuthProviderFactory.java

private static AuthProvider loadProvider(final String id, final Properties props) throws Exception {
    Class<?> obj = providerMap.get(id);
    props.setProperty("id", id);
    AuthProvider provider;/*from ww w . j a va2  s.  c o  m*/
    OAuthConfig conf;

    if (obj == null) {
        try {
            new URL(id); // just validating, don't need the value
            obj = providerMap.get("openid");
            conf = new OAuthConfig(null, null);
            conf.setId(id);
        } catch (MalformedURLException me) {
            throw new SocialAuthException(id + " is not a provider or valid OpenId URL");
        }
    } else {
        String key;
        if (domainMap.containsKey(id)) {
            key = domainMap.get(id);
        } else {
            key = id;
        }
        String consumerKey = props.getProperty(key + ".consumer_key");
        if (consumerKey == null) {
            throw new IllegalStateException(key + ".consumer_key not found.");
        }

        String consumerSecret = props.getProperty(key + ".consumer_secret");
        if (consumerSecret == null) {
            throw new IllegalStateException(key + ".consumer_secret not found.");
        }
        conf = new OAuthConfig(consumerKey, consumerSecret);
        conf.setId(id);
    }

    try {
        Constructor<?> cons = obj.getConstructor(OAuthConfig.class);
        provider = (AuthProvider) cons.newInstance(conf);
    } catch (NoSuchMethodException me) {
        LOG.warn(obj.getName() + " does not implement a constructor " + obj.getName()
                + "(OAuthConfig providerConfig)");
        provider = (AuthProvider) obj.newInstance();
    } catch (Exception e) {
        throw new SocialAuthConfigurationException(e);
    }
    return provider;
}

From source file:com.lenovo.tensorhusky.common.utils.ResourceCalculatorProcessTree.java

/**
 * Create the ResourceCalculatorProcessTree rooted to specified process
 * from the class name and configure it. If class name is null, this method
 * will try and return a process tree plugin available for this system.
 *
 * @param pid   process pid of the root of the process tree
 * @param clazz class-name/*from  w w w. j  av  a  2  s. c  o  m*/
 * @param conf  configure the plugin with this.
 * @return ResourceCalculatorProcessTree or null if ResourceCalculatorPluginTree
 * is not available for this system.
 */
public static ResourceCalculatorProcessTree getResourceCalculatorProcessTree(String pid,
        Class<? extends ResourceCalculatorProcessTree> clazz, HuskyConfiguration conf) {

    if (clazz != null) {
        try {
            Constructor<? extends ResourceCalculatorProcessTree> c = clazz.getConstructor(String.class);
            ResourceCalculatorProcessTree rctree = c.newInstance(pid);
            rctree.setConf(conf);
            return rctree;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // No class given, try a os specific class
    if (ProcfsBasedProcessTree.isAvailable()) {
        return new ProcfsBasedProcessTree(pid);
    }
    if (WindowsBasedProcessTree.isAvailable()) {
        return new WindowsBasedProcessTree(pid);
    }

    // Not supported on this system.
    return null;
}

From source file:com.alibaba.wasp.util.JVMClusterUtil.java

/**
 * Creates a {@link FServerThread}./*from w w w  .ja  v  a2s .c  om*/
 * Call 'start' on the returned thread to make it run.
 * @param c Configuration to use.
 * @param hrsc Class to create.
 * @param index Used distinguishing the object returned.
 * @throws java.io.IOException
 * @return FServer added.
 */
public static JVMClusterUtil.FServerThread createFServerThread(final Configuration c,
        final Class<? extends FServer> hrsc, final int index) throws IOException {
    FServer server;
    try {
        Constructor<? extends FServer> ctor = hrsc.getConstructor(Configuration.class);
        ctor.setAccessible(true);
        server = ctor.newInstance(c);
    } catch (InvocationTargetException ite) {
        Throwable target = ite.getTargetException();
        throw new RuntimeException("Failed construction of FServer: " + hrsc.toString()
                + ((target.getCause() != null) ? target.getCause().getMessage() : ""), target);
    } catch (Exception e) {
        IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    }
    return new JVMClusterUtil.FServerThread(server, index);
}

From source file:ClassUtil.java

/**
 * Returns a new instance of an object using constructor with
 * specified parameter types and arguments.
 *
 * @param name class name//from   w  ww .j  a v a 2s .  c o  m
 * @param param constructor parameter types
 * @param args constructor initialization arguments
 * @param logException constructor initialization arguments
 *
 * @return a new object instance or null if some error occours (exceptions are logged)
 */
public static Object newInstance(String name, Class param[], Object args[], boolean logException) {
    if (param == null && args != null) {
        param = new Class[args.length];
        for (int i = 0; i < param.length; i++) {
            if (args[i] != null) {
                param[i] = args[i].getClass();
            } else {
                param[i] = null;
            }
        } //for
    } //if

    Constructor c = null;
    Object obj = null;
    try {
        c = Class.forName(name).getConstructor(param);
        if (c != null) {
            obj = c.newInstance(args);
        }
    } catch (Exception x) {
        if (logException) {
            //   Logger log = Logger.getLogger(ClassUtil.class);
            //   log.error("", x);
        }
        return null;
    }
    return obj;
}

From source file:gpframework.RunExperiment.java

/**
 * Generates an object from a parameter value.
 * @param <T> type of the return parameter.
 * @param className name of the subclass to instantiate.
 * @return an instantiated object of type className.
 *///from  w w w . j a  va2s  .  c o  m
@SuppressWarnings("unchecked")
public synchronized static <T> T fromName(String className, Object... parameters) {

    // Get array of classes (to find right constructor)
    Class[] classes = new Class[parameters.length];
    for (int p = 0; p < parameters.length; p++) {
        // Integer must be transformed to int
        if (parameters[p].getClass() == Integer.class) {
            classes[p] = int.class;
        } else {
            // Find superclass
            Class currentClass = parameters[p].getClass();
            while (currentClass.getSuperclass() != Object.class)
                currentClass = currentClass.getSuperclass();

            classes[p] = currentClass;
        }
    }

    // Packages where to look for the class
    String[] packages = { "gpframework", "gpframework.algorithms", "gpframework.algorithms.components",
            "gpframework.algorithms.components.mutations", "gpframework.algorithms.components.selections",
            "gpframework.algorithms.components.selections", "gpframework.indicators",
            "gpframework.indicators.sorting", "gpframework.indicators.order", "gpframework.indicators.majority",
            "gpframework.program", "gpframework.program.sorting", "gpframework.program.ordermajority", };

    // Instantiated object
    T t = null;

    // Scan packages
    for (String packageName : packages) {
        try {
            Constructor<T> constructor = (Constructor<T>) Class.forName(packageName + "." + className)
                    .getConstructor(classes);
            t = constructor.newInstance(parameters);
            break;
        } catch (Exception e) {
            /* Keep going */ }
    }

    if (t == null)
        System.out.println("Object not created " + className
                + ", check your class name or look into fromClass() method for a solution.");

    return t;
}

From source file:com.frostwire.android.gui.UniversalScanner.java

private static Uri nativeScanFile(Context context, String path) {
    try {/*  ww  w . j a v a 2 s.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);

        try {
            Method setLocaleM = clazz.getDeclaredMethod("setLocale", String.class);
            setLocaleM.invoke(scanner, Locale.US.toString());
        } catch (Throwable e) {
            e.printStackTrace();
        }

        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
        }

        try {
            Field mFileCacheF = clazz.getDeclaredField("mNoMediaPaths");
            mFileCacheF.setAccessible(true);
            mFileCacheF.set(scanner, new HashMap<String, String>());
        } catch (Throwable e) {
            e.printStackTrace();
        }

        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:org.eel.kitchen.jsonschema.keyword.KeywordFactory.java

/**
 * Build one validator/*  w  w w .  j  a  va  2 s  .  c  om*/
 *
 * <p>This is done by reflection. Remember that the contract is to have a
 * constructor which takes a {@link JsonNode} as an argument.
 * </p>
 *
 * <p>If instantiation fails for whatever reason, an "invalid validator" is
 * returned which always fails.</p>
 *
 * @see #invalidValidator(Class, Exception)
 *
 * @param c the keyword validator class
 * @param schema the schema
 * @return the instantiated keyword validator
 */
private static KeywordValidator buildValidator(final Class<? extends KeywordValidator> c,
        final JsonNode schema) {
    final Constructor<? extends KeywordValidator> constructor;

    try {
        constructor = c.getConstructor(JsonNode.class);
    } catch (NoSuchMethodException e) {
        return invalidValidator(c, e);
    }

    try {
        return constructor.newInstance(schema);
    } catch (InstantiationException e) {
        return invalidValidator(c, e);
    } catch (IllegalAccessException e) {
        return invalidValidator(c, e);
    } catch (InvocationTargetException e) {
        return invalidValidator(c, e);
    }
}

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

/**
* Parses object with follow rules://from w  w w .  j a  va 2s.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 String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
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;
}