Example usage for java.lang Class newInstance

List of usage examples for java.lang Class newInstance

Introduction

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

Prototype

@CallerSensitive
@Deprecated(since = "9")
public T newInstance() throws InstantiationException, IllegalAccessException 

Source Link

Document

Creates a new instance of the class represented by this Class object.

Usage

From source file:com.openteach.diamond.container.Container.java

@SuppressWarnings("unchecked")
private static void initLifecycleListeners() {
    try {/*ww  w.  jav a  2 s.  co m*/
        Enumeration<URL> cUrls = Container.class.getClassLoader().getResources(DIAMOND_LIFECYCLE_FILE);
        while (cUrls.hasMoreElements()) {
            URL url = cUrls.nextElement();
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(url.openStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    try {
                        Class clazz = Container.class.getClassLoader().loadClass(line.trim());
                        if (LifecycleListener.class.isAssignableFrom(clazz)) {
                            lifecycleListeners.add((LifecycleListener) clazz.newInstance());
                        }
                    } catch (ClassNotFoundException e) {
                        System.err.println("?" + line);
                        e.printStackTrace();
                    }
                    //?
                    break;
                }
            } catch (IOException e) {
                logger.error(e);
            } finally {
                if (null != br) {
                    br.close();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println("?diamond!  " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.impetus.kundera.proxy.cglib.CglibLazyInitializer.java

/**
 * Gets the proxy instance./*from www.j  a  v a2s  .c o m*/
 * 
 * @param factory
 *            the factory
 * @param instance
 *            the instance
 * @return the proxy instance
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 */
private static KunderaProxy getProxyInstance(Class factory, CglibLazyInitializer instance)
        throws InstantiationException, IllegalAccessException {
    KunderaProxy proxy;
    try {
        Enhancer.registerCallbacks(factory, new Callback[] { instance, null });
        proxy = (KunderaProxy) factory.newInstance();
    } finally {
        Enhancer.registerCallbacks(factory, null);
    }
    return proxy;
}

From source file:com.stgmastek.core.comm.main.StartCoreCommunication.java

static void start() throws Exception {
    // Cache the clients
    ClientBook.getBook();/*from   ww w  .  j av a2s  .c o m*/

    // Loads or UP all the services as configured in the CORE_CONFIG table
    for (int i = 0; i < servicesList.size(); i++) {
        DeploymentMap map = servicesList.get(i);

        Class<? extends ServiceBase> serviceClass = map.getServiceInterface();
        Class<?> serviceImpl = map.getServiceImpl();

        WSServerAddress address = new WSServerAddress();
        address.setHost(map.getAddress());
        address.setPort(Integer.valueOf(map.getPort()));
        address.setDomain(serviceClass.getSimpleName());

        WSServerInfo info = new WSServerInfo(serviceClass.getSimpleName(), address);
        WSServerManager.getInstance().createServer(serviceClass, serviceImpl.newInstance(), info);
        if (logger.isEnabledFor(LogLevel.NOTICE)) {
            logger.log(LogLevel.NOTICE,
                    "Setting the server's publish address to be " + info.getAddress().getAddressURL());
            logger.log(LogLevel.NOTICE, "Starting services : " + serviceClass.getSimpleName());
        }
    }

    // Start the poller
    pollers.add(new OutBoundQueuePoller());
    for (BasePoller poller : pollers) {
        new Thread(poller).start();
    }
}

From source file:net.jradius.packet.PacketFactory.java

public static RadiusPacket parseUDP(int code, int identifier, int length, ByteBuffer buffer, boolean pool)
        throws RadiusException, IOException {
    RadiusPacket rp = null;/*w ww . ja va 2 s  . c  om*/
    Integer key = new Integer(code);

    if (pktObjectPool != null && pool) {
        try {
            rp = (RadiusPacket) pktObjectPool.borrowObject(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (rp == null) {
        Class<?> c = (Class<?>) codeMap.get(key);

        if (c == null) {
            throw new RadiusException("bad radius code - " + key);
        }

        try {
            rp = (RadiusPacket) c.newInstance();
        } catch (Exception e) {
            RadiusLog.error(e.getMessage(), e);
            return null;
        }
    }

    byte[] bAuthenticator = new byte[16];
    buffer.get(bAuthenticator);

    rp.setIdentifier(identifier);
    rp.setAuthenticator(bAuthenticator);

    length -= RadiusPacket.RADIUS_HEADER_LENGTH;
    if (length > 0) {
        RadiusFormat.setAttributeBytes(rp, buffer, length);
    }

    return rp;
}

From source file:de.cosmocode.palava.core.Palava.java

/**
 * Creates a new {@link Framework} using the specified properties.
 * <p>/*from  w  ww .java  2s  .  c  o m*/
 *   This method creates a new instance of the given module class using
 *   {@link Class#newInstance()}. As a consequence this class must provide
 *   a public no argument constructor.
 * </p>
 * <p>
 *   The specified properties will be bound using the {@link Settings} annotation.
 * </p>
 * 
 * @since 2.3
 * @param moduleClass the class literal of the main module
 * @param properties the application properties
 * @return a new configured {@link Framework} instance
 * @throws NullPointerException if mainModuleClass or properties is null
 * @throws IllegalArgumentException if creating instance of mainModuleClass failed
 * @throws ConfigurationException if guice configuration failed
 * @throws ProvisionException if providing an instance during creation failed
 */
public static Framework newFramework(Class<? extends Module> moduleClass, Properties properties) {
    Preconditions.checkNotNull(moduleClass, "ModuleClass");
    Preconditions.checkNotNull(properties, "Properties");

    final Module module;

    try {
        module = moduleClass.newInstance();
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException(e);
    }

    return newFramework(module, properties);
}

From source file:info.magnolia.cms.gui.dialog.DialogFactory.java

/**
 * Get a instance by the control type name. Those name class mappings are configured in the admin interface
 * configuration./*from w w  w .ja va  2  s  . c om*/
 * @param request
 * @param response
 * @param storageNode the node holding the data (can be null)
 * @param configNode the node holding the configuration (can be null)
 * @param controlType the name of the control
 * @return the conrol
 * @throws RepositoryException
 */
public static DialogControl getDialogControlInstanceByName(HttpServletRequest request,
        HttpServletResponse response, Content storageNode, Content configNode, String controlType)
        throws RepositoryException {

    Class dialogClass = (Class) controls.get(controlType);

    if (dialogClass == null) {
        try {
            dialogClass = Class.forName(controlType);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Unknown control type: \"" + controlType + "\""); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    DialogControl control = null;
    try {
        control = (DialogControl) dialogClass.newInstance();
    } catch (Exception e) {
        // should never happen
        throw new NestableRuntimeException("Unable to instantiate " //$NON-NLS-1$
                + dialogClass + " due to: InstantiationException - " //$NON-NLS-1$
                + e.getMessage());
    }

    control.init(request, response, storageNode, configNode);
    return control;
}

From source file:net.jradius.packet.PacketFactory.java

public static RadiusPacket parsePacket(ByteBuffer buffer) throws RadiusException {
    RadiusPacket rp = null;//  w w w .j a va 2s.c o  m
    int code = (int) Format.getUnsignedInt(buffer);
    int identifier = (int) Format.getUnsignedInt(buffer);
    long length = Format.getUnsignedInt(buffer);

    Integer key = new Integer(code);

    if (pktObjectPool != null) {
        try {
            rp = (RadiusPacket) pktObjectPool.borrowObject(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (rp == null) {
        Class<?> c = (Class<?>) codeMap.get(key);
        if (c == null) {
            throw new RadiusException("bad radius packet type: " + code);
        }
        try {
            rp = (RadiusPacket) c.newInstance();
        } catch (Exception e) {
            RadiusLog.error(e.getMessage(), e);
        }
    }

    try {
        rp.setIdentifier(identifier);
        FreeRadiusFormat.setAttributeBytes(rp, buffer, (int) length);
        //buffer.position(buffer.position() + (int) length);
    } catch (Exception e) {
        RadiusLog.error(e.getMessage(), e);
    }
    return rp;
}

From source file:com.fengduo.bee.commons.core.lang.ClassLoaderUtils.java

public static List<?> load(String classpath, ClassFilter filter) throws Exception {
    List<Object> objs = new ArrayList<Object>();
    URL resource = ClassLoaderUtils.class.getClassLoader().getResource(classpath);
    logger.debug("Search from {} ...", resource.getPath());
    List<String> classnameArray;
    if ("jar".equalsIgnoreCase(resource.getProtocol())) {
        String file = resource.getFile();
        String jarName = file.substring(file.indexOf("/"), (file.lastIndexOf("jar") + 3));
        classnameArray = getClassNamesInPackage(jarName, classpath);
    } else {//w w w  .  j av  a  2 s. c om
        Collection<File> listFiles = FileUtils.listFiles(new File(resource.getPath()), null, false);
        String classNamePrefix = classpath.replaceAll("/", ".");
        classnameArray = new ArrayList<String>();
        for (File file : listFiles) {
            String name = file.getName();
            if (name.endsWith(".class") == false) {
                continue;
            }
            if (StringUtils.contains(name, '$')) {
                logger.warn("NOT SUPPORT INNERT CLASS" + file.getAbsolutePath());
                continue;
            }
            String classname = classNamePrefix + "." + StringUtils.remove(name, ".class");
            classnameArray.add(classname);
        }
    }

    for (String classname : classnameArray) {
        try {
            Class<?> loadClass = ClassLoaderUtils.class.getClassLoader().loadClass(classname);
            if (filter != null && !filter.filter(loadClass)) {
                logger.error("{}  {} ", classname, filter);
                continue;
            }
            // if (ClassLoaderUtil.class.isAssignableFrom(loadClass) == false) {
            // logger.error("{} ?????", classname);
            // continue;
            // }
            Object newInstance = loadClass.newInstance();
            objs.add(newInstance);
            logger.debug("load {}/{}.class success", resource.getPath(), classname);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("load " + resource.getPath() + "/" + classname + ".class failed", e);
        }
    }
    return objs;
}

From source file:eu.stratosphere.nephele.jobmanager.JobManagerUtils.java

/**
 * Tries to locate a class with given name and to
 * instantiate a instance manager from it.
 * //from w  w w .  ja va  2  s  . c om
 * @param instanceManagerClassName
 *        the name of the class to instantiate the instance manager object from
 * @return the {@link InstanceManager} object instantiated from the class with the provided name
 */
@SuppressWarnings("unchecked")
static InstanceManager loadInstanceManager(final String instanceManagerClassName) {

    Class<? extends InstanceManager> instanceManagerClass;
    try {
        instanceManagerClass = (Class<? extends InstanceManager>) Class.forName(instanceManagerClassName);
    } catch (ClassNotFoundException e) {
        LOG.error("Cannot find class " + instanceManagerClassName + ": " + StringUtils.stringifyException(e));
        return null;
    }

    InstanceManager instanceManager;

    try {
        instanceManager = instanceManagerClass.newInstance();
    } catch (InstantiationException e) {
        LOG.error("Cannot create instanceManager: " + StringUtils.stringifyException(e));
        return null;
    } catch (IllegalAccessException e) {
        LOG.error("Cannot create instanceManager: " + StringUtils.stringifyException(e));
        return null;
    }

    return instanceManager;
}

From source file:com.huawei.streaming.cql.executor.operatorinfocreater.OperatorInfoCreatorFactory.java

private static OperatorInfoCreator createOperatorInfoInstance(Operator operator) throws ExecutorException {
    Class<? extends OperatorInfoCreator> creatorClass = AnnotationUtils
            .getOperatorCreatorAnnotation(operator.getClass());
    if (creatorClass == null) {
        ExecutorException exception = new ExecutorException(ErrorCode.SEMANTICANALYZE_UNKOWN_CLASS);
        LOG.error("Unkown operator class.", exception);
        throw exception;
    }/*from  w  w  w.j  a v a 2  s .  co m*/

    try {
        return creatorClass.newInstance();
    } catch (ReflectiveOperationException e) {
        ExecutorException exception = new ExecutorException(ErrorCode.SEMANTICANALYZE_UNKOWN_CLASS,
                operator.getClass().getName());
        LOG.error("Failed to create operator class instance.", exception);

        throw exception;
    }
}