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.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Helper method to create an object based on a class name specified in the properties file. Note
 * that all classes instantiated here must provide an empty constructor.
 *
 * @param clazz the super class of the object to be created
 * @param property the property that has the class name as a value
 * @param context holding shared objects during the optimization process
 * @return the instantiated object/*from  ww  w  .  j  a va  2  s. c om*/
 * @throws KeywordOptimizerException in case of a problem lading the specified object
 */
@SuppressWarnings(value = "unchecked")
private static <Type> Type createObjectBasedOnProperty(Class<Type> clazz, KeywordOptimizerProperty property,
        OptimizationContext context) throws KeywordOptimizerException {
    String className = context.getConfiguration().getString(property.getName());
    if (className == null || className.isEmpty()) {
        throw new KeywordOptimizerException("Mandatory property '" + property.getName() + "' is missing");
    }

    try {
        Class<Type> dynamicClazz = (Class<Type>) Class.forName(className);

        // First try if there is a constructor expecting the optimization context.
        try {
            Constructor<Type> constructor = dynamicClazz.getConstructor(OptimizationContext.class);
            Type obj = constructor.newInstance(context);
            return clazz.cast(obj);
        } catch (NoSuchMethodException e) {
            // Ignore.
        }

        // Else use default constructor.
        Constructor<Type> constructor = dynamicClazz.getConstructor();
        Type obj = constructor.newInstance();
        return clazz.cast(obj);
    } catch (ReflectiveOperationException e) {
        throw new KeywordOptimizerException("Error constructing '" + className + "'");
    }
}

From source file:com.connectsdk.service.DeviceService.java

public static DeviceService getService(Class<? extends DeviceService> clazz, ServiceConfig serviceConfig) {
    try {//from   w w w  .  j a v  a2s . c  om
        Constructor<? extends DeviceService> constructor = clazz.getConstructor(ServiceConfig.class);

        return constructor.newInstance(serviceConfig);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.red5.server.api.persistence.PersistenceUtils.java

/**
 * Returns persistence store object. Persistence store is a special object that stores persistence objects and provides methods to manipulate them (save, load, remove, list).
 * //from  w  w  w.j ava 2s.c om
 * @param resolver
 *            Resolves connection pattern into Resource object
 * @param className
 *            Name of persistence class
 * @return IPersistence store object that provides methods for persistence object handling
 * @throws Exception
 *             if error
 */
public static IPersistenceStore getPersistenceStore(ResourcePatternResolver resolver, String className)
        throws Exception {
    Class<?> persistenceClass = Class.forName(className);
    Constructor<?> constructor = getPersistenceStoreConstructor(persistenceClass,
            resolver.getClass().getInterfaces());
    if (constructor == null) {
        // Search in superclasses of the object.
        Class<?> superClass = resolver.getClass().getSuperclass();
        while (superClass != null) {
            constructor = getPersistenceStoreConstructor(persistenceClass, superClass.getInterfaces());
            if (constructor != null) {
                break;
            }
            superClass = superClass.getSuperclass();
        }
    }
    if (constructor == null) {
        throw new NoSuchMethodException();
    }
    return (IPersistenceStore) constructor.newInstance(new Object[] { resolver });
}

From source file:com.xhsoft.framework.common.utils.ClassUtil.java

/**
 * /*w  ww .ja va 2  s  .  c  o m*/
 * @param className
 * @param parent
 * @param parameters
 * @return
 * @throws ClassNotFoundException
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException - Object
 * @author: lizj
 */
public static Object getInstance(String className, String parent, Object[] parameters)
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Class<?> clazz = ClassUtil.getClass(className, parent);

    Class<?>[] types = null;

    if (parameters == null) {
        types = new Class[0];
    } else {
        types = new Class[parameters.length];
    }

    Constructor<?> c = clazz.getConstructor(types);

    return c.newInstance(parameters);
}

From source file:com.xhsoft.framework.common.utils.ClassUtil.java

/**
 * //from  w w  w . j  av a  2s.  c om
 * @param className
 * @param parent
 * @param parameterTypes
 * @param parametersObjects
 * @return
 * @throws ClassNotFoundException
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException - Object
 * @author: lizj
 */
public static Object getInstance(String className, String parent, Class<?>[] parameterTypes,
        Object[] parametersObjects) throws ClassNotFoundException, SecurityException, NoSuchMethodException,
        IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
    Class<?> clazz = ClassUtil.getClass(className, parent);

    Constructor<?> c = clazz.getConstructor(parameterTypes);

    return c.newInstance(parametersObjects);
}

From source file:com.fatminds.cmis.AlfrescoCmisHelper.java

public static Object convert(Object inVal, Class<?> outClass) {
    if (null == inVal || null == outClass) {
        //log.info("inVal " + inVal + " or outClass " + outClass + " are null");
        return null;
    }//  w  ww. j av  a2 s.co  m
    //log.info("Converting " + inVal.getClass() + " to " + outClass);
    if (outClass.isAssignableFrom(inVal.getClass()))
        return inVal;

    Object outVal;
    try {
        Constructor<?> c = outClass.getConstructor(inVal.getClass());
        outVal = c.newInstance(inVal);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        //log.info("Failed to find constructor of " + outClass.toString() 
        //      + " with input parameter " + inVal.getClass().toString()
        //      + ", returning unconverted value");
        outVal = inVal;
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
    //log.info("Returning an instance of " + outVal.getClass());
    return outVal;
}

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

public static Object instantiateObject(final Class inClass, final Object[] args) {
    Constructor constructor = null;

    if (inClass == null) {
        throw new IllegalArgumentException("inClass can not be null.");
    }/*w  ww  .jav  a  2  s . co  m*/

    try {
        constructor = inClass.getDeclaredConstructor(getClassArrayFromObjectArray(args));

        return constructor.newInstance(args);
    } catch (final Exception e) {
        throw new RuntimeException("Error trying to instatiate class, '" + inClass.getName() + "'.  Error:  "
                + e.getClass().getName() + ":  " + e.getMessage() + ".");
    }
}

From source file:Browser.java

/**
 * Called by a static initializer to load any classes, fields, and methods 
 * required at runtime to locate the user's web browser.
 * @return <code>true</code> if all intialization succeeded
 *         <code>false</code> if any portion of the initialization failed
 *///from ww  w . ja v a  2  s  .co  m
private static boolean loadClasses() {
    switch (jvm) {
    case MRJ_2_0:
        try {
            Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
            Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
            Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
            Class aeClass = Class.forName("com.apple.MacOS.ae");
            aeDescClass = Class.forName("com.apple.MacOS.AEDesc");

            aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[] { int.class });
            appleEventConstructor = appleEventClass.getDeclaredConstructor(
                    new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
            aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });

            makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class[] { String.class });
            putParameter = appleEventClass.getDeclaredMethod("putParameter",
                    new Class[] { int.class, aeDescClass });
            sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] {});

            Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
            keyDirectObject = (Integer) keyDirectObjectField.get(null);
            Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
            kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
            Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
            kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;

    case MRJ_2_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
            Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
            kSystemFolderType = systemFolderField.get(null);
            findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
            getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
            getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (SecurityException se) {
            errorMessage = se.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;

    case MRJ_3_0:
        try {
            Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
            Constructor constructor = linker.getConstructor(new Class[] { Class.class });
            linkage = constructor.newInstance(new Object[] { Browser.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (InvocationTargetException ite) {
            errorMessage = ite.getMessage();
            return false;
        } catch (InstantiationException ie) {
            errorMessage = ie.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;

    case MRJ_3_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        }
        break;

    default:
        break;
    }
    return true;
}

From source file:Main.java

/**
 * Takes a class type and constructs it. If the class does not have an empty constructor this
 * will/* ww w . j a  v a 2 s.  c  om*/
 * find the parametrized constructor and use nulls and default values to construct the class.
 *
 * @param clazz The class to construct.
 * @param <T> The type of the class to construct.
 * @return The constructed object.
 */
public static <T> T createInstance(Class<T> clazz) {
    T created = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
        if (!Modifier.isPrivate(constructor.getModifiers())) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            List<Object> params = new ArrayList<Object>();
            for (Class<?> parameterType : parameterTypes)
                if (!parameterType.isPrimitive()) {
                    params.add(null);
                } else {
                    if (parameterType == boolean.class) {
                        params.add(false);
                    } else {
                        params.add(0);
                    }
                }

            try {
                @SuppressWarnings("unchecked")
                T newObject = (T) constructor.newInstance(params.toArray());
                created = newObject;
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            break;
        }
    }
    return created;
}

From source file:fxts.stations.util.BrowserLauncher.java

/**
 * Called by a static initializer to load any classes, fields, and methods required at runtime
 * to locate the user's web browser.//from w  w w . ja  v a  2 s.c o  m
 *
 * @return <code>true</code> if all intialization succeeded
 *         <code>false</code> if any portion of the initialization failed
 */
private static boolean loadClasses() {
    switch (jvm) {
    case MRJ_2_0:
        try {
            Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
            Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
            Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
            Class aeClass = Class.forName("com.apple.MacOS.ae");
            aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
            aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[] { int.class });
            appleEventConstructor = appleEventClass.getDeclaredConstructor(
                    new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
            aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
            makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class[] { String.class });
            putParameter = appleEventClass.getDeclaredMethod("putParameter",
                    new Class[] { int.class, aeDescClass });
            sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] {});
            Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
            keyDirectObject = (Integer) keyDirectObjectField.get(null);
            Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
            kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
            Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
            kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;
    case MRJ_2_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
            Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
            kSystemFolderType = systemFolderField.get(null);
            findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
            getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
            getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (SecurityException se) {
            errorMessage = se.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;
    case MRJ_3_0:
        try {
            Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
            Constructor constructor = linker.getConstructor(new Class[] { Class.class });
            linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (InvocationTargetException ite) {
            errorMessage = ite.getMessage();
            return false;
        } catch (InstantiationException ie) {
            errorMessage = ie.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;
    case MRJ_3_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        }
        break;
    default:
        break;
    }
    return true;
}