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:Main.java

public static NetworkInfo createNetworkInfo(final int type, final boolean connected) throws Exception {
    Constructor<NetworkInfo> ctor = NetworkInfo.class.getDeclaredConstructor(int.class);
    ctor.setAccessible(true);//  w w  w  .j ava  2s . c  o  m
    NetworkInfo networkInfo = ctor.newInstance(0);
    Field typeField = NetworkInfo.class.getDeclaredField("mNetworkType");
    Field connectedField = NetworkInfo.class.getDeclaredField("mState");
    Field detailedStateField = NetworkInfo.class.getDeclaredField("mDetailedState");
    typeField.setAccessible(true);
    connectedField.setAccessible(true);
    detailedStateField.setAccessible(true);
    typeField.setInt(networkInfo, type);
    connectedField.set(networkInfo,
            connected == true ? NetworkInfo.State.CONNECTED : NetworkInfo.State.DISCONNECTED);
    detailedStateField.set(networkInfo,
            connected == true ? NetworkInfo.DetailedState.CONNECTED : NetworkInfo.DetailedState.DISCONNECTED);
    return networkInfo;
}

From source file:Main.java

public static Object newInstance(final Constructor<?> constructor, final Object... args) {
    if (constructor == null) {
        return null;
    }/*from w w w .j av a  2 s. co  m*/
    try {
        return constructor.newInstance(args);
    } catch (final InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        Log.e(TAG, "Exception in newInstance", e);
    }
    return null;
}

From source file:Main.java

public static <T> T newInstance(Class<T> type, Class<?>[] argsClass, Object[] argsValues)
        throws InstantiationException, IllegalAccessException {
    T instance = null;/* w  w  w.j  a  va2s  .c om*/
    try {
        Constructor<T> constructorDef = type.getConstructor(argsClass);
        instance = constructorDef.newInstance(argsValues);
    } catch (SecurityException e) {
        throw new InstantiationException(e.getMessage());
    } catch (NoSuchMethodException e) {
        throw new InstantiationException(e.getMessage());
    } catch (IllegalArgumentException e) {
        throw new InstantiationException(e.getMessage());
    } catch (InvocationTargetException e) {
        throw new InstantiationException(e.getMessage());
    }
    return instance;
}

From source file:Main.java

public static Map<String, Object> getProperties(Element root) {
    Map<String, Object> map = new HashMap<String, Object>();
    Element[] list = getChildrenByName(root, "property");
    for (int i = 0; i < list.length; i++) {
        String name = list[i].getAttribute("name");
        String type = list[i].getAttribute("type");
        String valueString = getText(list[i]);
        try {/*ww w .  jav  a2s  .  c  o  m*/
            Class<?> cls = Class.forName(type);
            Constructor<?> con = cls.getConstructor(new Class<?>[] { String.class

            });
            Object value = con.newInstance(new Object[] { valueString

            });
            map.put(name, value);
        } catch (Exception e) {
            System.err.println("Unable to parse property '" + name +

                    "'='" + valueString + "': " + e.toString());
        }
    }
    return map;
}

From source file:com.inmobi.conduit.CheckpointProviderFactory.java

private static CheckpointProvider getProvider(InputStream in) throws Exception {
    CheckpointProvider provider = null;/*from  www . jav a 2s  .  c  o  m*/
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    try {
        String line;
        String providerName = null;
        String providerDir = null;
        do {
            line = reader.readLine();
            String[] keyVal = line.split("=");
            if (keyVal != null && keyVal.length == 2 && keyVal[0].equalsIgnoreCase(CHECKPOINT_PROVIDER)) {
                //provider = (CheckpointProvider) Class.forName(keyVal[1])
                //.newInstance();
                providerName = keyVal[1];
            }
            if (keyVal != null && keyVal.length == 2 && keyVal[0].equalsIgnoreCase(CHECKPOINT_PROVIDER_DIR)) {
                providerDir = keyVal[1];
            }
        } while (line != null);

        if (providerName != null && providerDir != null) {
            Class providerClass = Class.forName(providerName);
            Constructor constructor = providerClass.getConstructor(String.class);
            provider = (CheckpointProvider) constructor.newInstance(new Object[] { providerDir });
        }
    } catch (Exception e) {
        //return default provider
        LOG.debug("Error creating CheckPointProvider", e);
        return null;
    }
    return provider;
}

From source file:libepg.epg.section.descriptor.contentdescriptor.NIbbleMaker.java

public static final Nibble init(byte[] data) throws Throwable {
    try {/*from   ww  w .  j  av  a  2 s  . c  o  m*/
        Object[] args = { data };
        Class<?>[] params = { byte[].class };
        Constructor<Nibble> constructor = Nibble.class.getDeclaredConstructor(params);
        constructor.setAccessible(true);
        Nibble target = constructor.newInstance(args);
        return target;
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException
            | SecurityException ex) {
        LOG.fatal(ex);
    } catch (InvocationTargetException ex) {
        throw ex.getCause();
    }
    return null;
}

From source file:msi.gama.util.file.GamaFileMetaData.java

public static <T extends IGamaFileMetaData> T from(final String s, final long stamp, final Class<T> clazz,
        final boolean includeOutdated) {
    T result = null;/*from w  w  w  .j  a v  a2  s.  c om*/
    try {
        final Constructor<T> c = clazz.getDeclaredConstructor(String.class);
        result = c.newInstance(s);
        final boolean hasFailed = result.hasFailed();
        if (!hasFailed && !includeOutdated && result.getModificationStamp() != stamp) {
            return null;
        }
    } catch (final Exception ignore) {
        DEBUG.ERR("Error loading metadata " + s + " : " + ignore.getClass().getSimpleName() + ":"
                + ignore.getMessage());
        if (ignore instanceof InvocationTargetException && ignore.getCause() != null) {
            ignore.getCause().printStackTrace();
        }
    }
    return result;
}

From source file:it.greenvulcano.gvesb.http.ProtocolFactory.java

/**
 *
 * @param value//from w w w.  ja va 2s .c o m
 * @param cls
 * @return
 */
private static Object cast(String value, Class<?> cls) throws Exception {
    Class<?>[] types = { String.class };
    Constructor<?> constr = cls.getConstructor(types);
    Object[] params = { value };
    return constr.newInstance(params);
}

From source file:it.greenvulcano.gvesb.http.ProtocolFactory.java

/**
 *
 * @param objectClass/*from  w w w.j a  va  2 s.c  o m*/
 *        Object class to instantiate
 * @param node
 *        The configuration of constructor parameters.
 * @return
 */
private static Object createObjectUsingConstructor(Class<?> objectClass, Node node) throws Exception {
    NodeList paramList = XMLConfig.getNodeList(node, "constructor-param");
    Class<?>[] types = new Class[paramList.getLength()];
    Object[] params = new Object[types.length];

    for (int i = 0; i < types.length; ++i) {
        Node paramNode = paramList.item(i);
        String type = XMLConfig.get(paramNode, "@type");
        String value = XMLConfig.getDecrypted(paramNode, "@value");
        Class<?> cls = null;
        if (type.equals("byte")) {
            cls = Byte.TYPE;
        } else if (type.equals("boolean")) {
            cls = Boolean.TYPE;
        } else if (type.equals("char")) {
            cls = Character.TYPE;
        } else if (type.equals("double")) {
            cls = Double.TYPE;
        } else if (type.equals("float")) {
            cls = Float.TYPE;
        } else if (type.equals("int")) {
            cls = Integer.TYPE;
        } else if (type.equals("long")) {
            cls = Long.TYPE;
        } else if (type.equals("short")) {
            cls = Short.TYPE;
        } else if (type.equals("String")) {
            cls = String.class;
        }
        types[i] = cls;
        params[i] = cast(value, cls);
    }

    Constructor<?> constr = objectClass.getConstructor(types);
    return constr.newInstance(params);
}

From source file:com.conwet.silbops.msg.Message.java

public static Message fromJSON(JSONObject json) {

    try {/*from ww  w.j  a va2s .c  o  m*/
        MessageType type = MessageType.fromJSON((String) json.get("type"));
        Constructor<? extends Message> constructor = typeMap.get(type).getConstructor(JSONObject.class);
        return constructor.newInstance(json.get("payload"));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Malformed object[" + json.toJSONString() + "]", ex);
    }
}