Example usage for java.lang Class getConstructor

List of usage examples for java.lang Class getConstructor

Introduction

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

Prototype

@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Usage

From source file:coolmap.module.impl.SideMapModule.java

public static void registerSideMapRow(final Class<RowMap> rowMap) {

    rowMaps.add(rowMap);/*from w  w w. j av a  2s.c o  m*/
    //Also add to menu
    //        System.err.println(rowMap);

    try {
        MenuItem item = new MenuItem(
                ((RowMap) rowMap.getConstructor(CoolMapObject.class).newInstance(new CoolMapObject()))
                        .getName());

        CoolMapMaster.getCMainFrame().addMenuItem("View/Canvas config/Row side/", item, false, false);
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    CoolMapObject object = CoolMapMaster.getActiveCoolMapObject();
                    object.getCoolMapView()
                            .addRowMap(rowMap.getConstructor(CoolMapObject.class).newInstance(object));
                } catch (Exception ex) {
                    //                    ex.printStackTrace();
                    //need an error logging system
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:apple.dts.samplecode.osxadapter.OSXAdapter.java

public static void setHandler(OSXAdapter adapter) {
    try {/*from w w w. j a v a  2 s .com*/
        Class<?> applicationClass = Class.forName("com.apple.eawt.Application");
        if (macOSXApplication == null) {
            macOSXApplication = applicationClass.getConstructor((Class<?>[]) null).newInstance((Object[]) null);
        }
        Class<?> applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener");
        Method addListenerMethod = applicationClass.getDeclaredMethod("addApplicationListener",
                new Class<?>[] { applicationListenerClass });
        // Create a proxy object around this handler that can be reflectively added as an Apple ApplicationListener
        Object osxAdapterProxy = Proxy.newProxyInstance(OSXAdapter.class.getClassLoader(),
                new Class<?>[] { applicationListenerClass }, adapter);
        addListenerMethod.invoke(macOSXApplication, new Object[] { osxAdapterProxy });
    } catch (ClassNotFoundException cnfe) {
        System.err.println(
                "This version of Mac OS X does not support the Apple EAWT.  ApplicationEvent handling has been disabled ("
                        + cnfe + ")");
    } catch (Exception ex) { // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking eawt.Application methods
        log.error("Mac OS X Adapter could not talk to EAWT:", ex);
    }
}

From source file:com.kylinolap.common.persistence.ResourceStore.java

public static ResourceStore getStore(KylinConfig kylinConfig) {
    ResourceStore r = CACHE.get(kylinConfig);
    List<Throwable> es = new ArrayList<Throwable>();
    if (r == null) {
        logger.info("Using metadata url " + kylinConfig.getMetadataUrl() + " for resource store");
        for (Class<? extends ResourceStore> cls : knownImpl) {

            try {
                r = cls.getConstructor(KylinConfig.class).newInstance(kylinConfig);
            } catch (Exception e) {
                es.add(e);//  w  w w.  j  a  va 2  s  .  c  om
            } catch (NoClassDefFoundError er) {
                // may throw NoClassDefFoundError
                es.add(er);
            }
            if (r != null) {
                break;
            }
        }
        if (r == null) {
            for (Throwable exceptionOrError : es) {
                logger.error("Create new store instance failed ", exceptionOrError);
            }
            throw new IllegalArgumentException(
                    "Failed to find metadata store by url: " + kylinConfig.getMetadataUrl());
        }

        CACHE.put(kylinConfig, r);
    }
    return r;
}

From source file:com.opengamma.component.tool.ToolContextUtils.java

private static ToolContext createToolContextByHttp(String configResourceLocation,
        Class<? extends ToolContext> toolContextClazz, List<String> classifierChain) {
    configResourceLocation = StringUtils.stripEnd(configResourceLocation, "/");
    if (configResourceLocation.endsWith("/jax") == false) {
        configResourceLocation += "/jax";
    }//from   w  w w  . j a v a2  s .co  m

    // Get the remote component server using the supplied URI
    RemoteComponentServer remoteComponentServer = new RemoteComponentServer(URI.create(configResourceLocation));
    ComponentServer componentServer = remoteComponentServer.getComponentServer();

    // Attempt to build a tool context of the specified type
    ToolContext toolContext;
    try {
        toolContext = toolContextClazz.newInstance();
    } catch (Throwable t) {
        return null;
    }

    // Populate the tool context from the remote component server
    for (MetaProperty<?> metaProperty : toolContext.metaBean().metaPropertyIterable()) {
        if (!metaProperty.name().equals("contextManager")) {
            try {
                ComponentInfo componentInfo = getComponentInfo(componentServer, classifierChain,
                        metaProperty.propertyType());
                if (componentInfo == null) {
                    s_logger.warn("Unable to populate tool context '" + metaProperty.name()
                            + "', no appropriate component found on the server");
                    continue;
                }
                if (ViewProcessor.class.equals(componentInfo.getType())) {
                    final JmsConnector jmsConnector = createJmsConnector(componentInfo);
                    final ScheduledExecutorService scheduler = Executors
                            .newSingleThreadScheduledExecutor(new NamedThreadFactory("rvp"));
                    ViewProcessor vp = new RemoteViewProcessor(componentInfo.getUri(), jmsConnector, scheduler);
                    toolContext.setViewProcessor(vp);
                    toolContext.setContextManager(new Closeable() {
                        @Override
                        public void close() throws IOException {
                            scheduler.shutdownNow();
                            jmsConnector.close();
                        }
                    });
                } else {
                    String clazzName = componentInfo.getAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA);
                    if (clazzName == null) {
                        s_logger.warn("Unable to populate tool context '" + metaProperty.name()
                                + "', no remote access class found");
                        continue;
                    }
                    Class<?> clazz = Class.forName(clazzName);
                    metaProperty.set(toolContext,
                            clazz.getConstructor(URI.class).newInstance(componentInfo.getUri()));
                    s_logger.info("Populated tool context '" + metaProperty.name() + "' with "
                            + metaProperty.get(toolContext));
                }
            } catch (Throwable ex) {
                s_logger.warn(
                        "Unable to populate tool context '" + metaProperty.name() + "': " + ex.getMessage());
            }
        }
    }
    return toolContext;
}

From source file:org.objectweb.proactive.extensions.timitspmd.util.charts.Utilities.java

/**
 * Exports a JFreeChart to a SVG file.// www  .j  a v  a2  s .co  m
 *
 * @param chart
 *            JFreeChart to export
 * @param bounds
 *            the dimensions of the viewport
 * @param svgFile
 *            the output file.
 * @throws IOException
 *             if writing the svgFile fails.
 */
public static void saveChartAsSVG(JFreeChart chart, Rectangle bounds, File svgFile) throws IOException {
    try {
        Class<?> GDI = Class.forName("org.apache.batik.dom.GenericDOMImplementation");

        // Get a DOMImplementation and create an XML document
        Method getDOMImplementation = GDI.getMethod("getDOMImplementation", new Class<?>[0]);
        DOMImplementation domImpl = (DOMImplementation) getDOMImplementation.invoke(null, new Object[0]);

        org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);

        // Create an instance of the SVG Generator
        Class<?> SG2D = Class.forName("org.apache.batik.svggen.SVGGraphics2D");
        Method streamMethod = SG2D.getMethod("stream", new Class<?>[] { Writer.class, boolean.class });
        Constructor<?> SG2DConstr = SG2D.getConstructor(new Class<?>[] { org.w3c.dom.Document.class });
        Object svgGenerator = SG2DConstr.newInstance(document);

        // draw the chart in the SVG generator
        chart.draw((Graphics2D) svgGenerator, bounds);

        // Write svg file
        OutputStream outputStream = new FileOutputStream(svgFile);
        Writer out = new OutputStreamWriter(outputStream, "UTF-8");
        streamMethod.invoke(svgGenerator, new Object[] { out, true /* use css */ });
        outputStream.flush();
        outputStream.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:coolmap.module.impl.SideMapModule.java

public static void registerSideMapColumn(final Class<ColumnMap> columnMap) {
    columnMaps.add(columnMap);//from  ww w .ja  v  a  2s . co m
    //Also add to menu
    //        System.err.println(columnMap);
    try {
        MenuItem item = new MenuItem(
                ((ColumnMap) columnMap.getConstructor(CoolMapObject.class).newInstance(new CoolMapObject()))
                        .getName());
        CoolMapMaster.getCMainFrame().addMenuItem("View/Canvas config/Column side/", item, false, false);
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    CoolMapObject object = CoolMapMaster.getActiveCoolMapObject();
                    object.getCoolMapView()
                            .addColumnMap(columnMap.getConstructor(CoolMapObject.class).newInstance(object));
                } catch (Exception ex) {
                    //                    ex.printStackTrace();
                    //need an error logging system
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

/**
 * Creates a {@link MasterThread}.//from w w  w. j av a 2 s  .  co  m
 * Call 'start' on the returned thread to make it run.
 * @param c Configuration to use.
 * @param hmc Class to create.
 * @param index Used distinguishing the object returned.
 * @throws java.io.IOException
 * @return Master added.
 */
public static JVMClusterUtil.MasterThread createMasterThread(final Configuration c,
        final Class<? extends FMaster> hmc, final int index) throws IOException {
    FMaster server;
    try {
        server = hmc.getConstructor(Configuration.class).newInstance(c);
    } catch (InvocationTargetException ite) {
        Throwable target = ite.getTargetException();
        throw new RuntimeException("Failed construction of Master: " + hmc.toString()
                + ((target.getCause() != null) ? target.getCause().getMessage() : ""), target);
    } catch (Exception e) {
        IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    }
    return new JVMClusterUtil.MasterThread(server, index);
}

From source file:com.controlj.addon.weather.wbug.service.WeatherBugDataUtils.java

/**
 * Navigates a XML document through an XPath and, for each encountered element, creates a specific WeatherBug data object (<i>Location</i>,
 * <i>Station</i>, and so on). Java reflection errors are silently ignored.
 * /*from  w  ww  . j a v  a2 s  .c o m*/
 * @param elem
 *            the XML element being accessed.
 * @param path
 *            the XPath used to find specific sub-elements.
 * @param dataClass
 *            the class of objects being instantiated (<i>Location</i>, <i>Station</i>, and so on).
 * @return a list of <i>dataClass</i> objects.
 */
public static <T> List<T> bind(Element elem, String path, Class<T> dataClass) {
    Constructor<T> constr;
    try {
        constr = dataClass.getConstructor(ELEM_CLASS_ARRAY);
    } catch (SecurityException e) {
        return Collections.emptyList();
    } catch (NoSuchMethodException e) {
        return Collections.emptyList();
    }
    List<T> resultList = new ArrayList<T>();
    for (Object o : elem.selectNodes(path)) {
        Element item = (Element) o;
        try {
            resultList.add(constr.newInstance(item));
        } catch (IllegalArgumentException e) {
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
    }
    return resultList;
}

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

@SuppressWarnings("unchecked")
public static <T> Constructor<T> getConstructor(final String className, final Class<?>... parameterClasses) {
    try {/*from   w  w  w  .ja va 2 s .  c o  m*/
        final Class<T> clazz = (Class<T>) Class.forName(className);
        return clazz.getConstructor(parameterClasses);
    } catch (final NoSuchMethodException e) {
        return null;
    } catch (final Throwable e) {
        return Exceptions.throwUncheckedException(e);
    }
}

From source file:org.n52.server.util.SosAdapterFactory.java

/**
 * Creates an adapter to make requests to an SOS instance. If the given metadata does not contain a full qualified
 * class name defining the adapter implementation the default one is returned.
 *
 * @param metadata the SOS metadata where to create the SOS adapter implementation from.
 * @return the custom adapter implementation, or the default {@link SOSAdapter}.
 */// w  w w  .  ja v  a  2 s . co m
public static SOSAdapter createSosAdapter(SOSMetadata metadata) {
    String adapter = metadata.getAdapter();
    String sosVersion = metadata.getSosVersion();
    try {
        SOSAdapter sosAdapter = new SOSAdapter(sosVersion);
        sosAdapter.setHttpClient(createHttpClient(metadata));
        if (adapter == null) {
            return sosAdapter;
        } else {

            if (!SOSAdapter.class.isAssignableFrom(Class.forName(adapter))) {
                LOGGER.warn("'{}' is not an SOSAdapter implementation! Create default.", adapter);
                return sosAdapter;
            }
            @SuppressWarnings("unchecked") // unassignable case handled already
            Class<SOSAdapter> clazz = (Class<SOSAdapter>) Class.forName(adapter);
            Class<?>[] arguments = new Class<?>[] { String.class };
            Constructor<SOSAdapter> constructor = clazz.getConstructor(arguments);
            sosAdapter = constructor.newInstance(sosVersion);
            sosAdapter.setHttpClient(createHttpClient(metadata));
            return sosAdapter;
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Could not find Adapter class '" + adapter + "'.", e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Invalid Adapter constructor for '" + adapter + "'.", e);
    } catch (InstantiationException e) {
        throw new RuntimeException("Could not create Adapter for '" + adapter + "'.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Not allowed to create Adapter for '" + adapter + "'.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Instantiation failed for Adapter " + adapter + "'.", e);
    }
}