Example usage for java.lang Object getClass

List of usage examples for java.lang Object getClass

Introduction

In this page you can find the example usage for java.lang Object getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    String WRITE_OBJECT_SQL = "BEGIN " + "  INSERT INTO java_objects(object_id, object_name, object_value) "
            + "  VALUES (?, ?, empty_blob()) " + "  RETURN object_value INTO ?; " + "END;";
    String READ_OBJECT_SQL = "SELECT object_value FROM java_objects WHERE object_id = ?";

    Connection conn = getOracleConnection();
    conn.setAutoCommit(false);/*from  w  w w  . j a va 2  s .  c om*/
    List<Object> list = new ArrayList<Object>();
    list.add("This is a short string.");
    list.add(new Integer(1234));
    list.add(new java.util.Date());

    // write object to Oracle
    long id = 0001;
    String className = list.getClass().getName();
    CallableStatement cstmt = conn.prepareCall(WRITE_OBJECT_SQL);

    cstmt.setLong(1, id);
    cstmt.setString(2, className);

    cstmt.registerOutParameter(3, java.sql.Types.BLOB);

    cstmt.executeUpdate();
    BLOB blob = (BLOB) cstmt.getBlob(3);
    OutputStream os = blob.getBinaryOutputStream();
    ObjectOutputStream oop = new ObjectOutputStream(os);
    oop.writeObject(list);
    oop.flush();
    oop.close();
    os.close();

    // Read object from oracle
    PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL);
    pstmt.setLong(1, id);
    ResultSet rs = pstmt.executeQuery();
    rs.next();
    InputStream is = rs.getBlob(1).getBinaryStream();
    ObjectInputStream oip = new ObjectInputStream(is);
    Object object = oip.readObject();
    className = object.getClass().getName();
    oip.close();
    is.close();
    rs.close();
    pstmt.close();
    conn.commit();

    // de-serialize list a java object from a given objectID
    List listFromDatabase = (List) object;
    System.out.println("[After De-Serialization] list=" + listFromDatabase);
    conn.close();
}

From source file:Main.java

public static void main(String[] argv) {
    DefaultTableModel model = new DefaultTableModel() {
        public Class getColumnClass(int columnIndex) {
            Object o = getValueAt(0, columnIndex);
            if (o == null) {
                return Object.class;
            } else {
                return o.getClass();
            }//from  www. ja v a2 s . co  m
        }
    };
    JTable table = new JTable(model);

    model.addColumn("Boolean", new Object[] { Boolean.TRUE });
    model.addColumn("Date", new Object[] { new Date() });
    model.addColumn("Double", new Object[] { new Double(Math.PI) });
    model.addColumn("Float", new Object[] { new Float(1.2) });
    model.addColumn("Icon", new Object[] { new ImageIcon("icon.gif") });
    model.addColumn("Number", new Object[] { new Integer(1) });
    model.addColumn("Object", new Object[] { "object" });

    Enumeration e = table.getColumnModel().getColumns();
    TableColumn col = (TableColumn) e.nextElement();

    col.setCellRenderer(table.getDefaultRenderer(Boolean.class));
    col.setCellEditor(table.getDefaultEditor(Boolean.class));

    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.add(new JScrollPane(table));
    f.setVisible(true);
}

From source file:TypeMapDemo.java

public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {

    Properties p = new Properties();
    p.load(new FileInputStream("db.properties"));
    Class c = Class.forName(p.getProperty("db.driver"));
    System.out.println("Loaded driverClass " + c.getName());

    Connection con = DriverManager.getConnection(p.getProperty("db.url"), "student", "student");
    System.out.println("Got Connection " + con);

    Statement s = con.createStatement();
    int ret;//from  w  w w.  j a v a2s . co  m
    try {
        s.executeUpdate("drop table MR");
        s.executeUpdate("drop type MUSICRECORDING");
    } catch (SQLException andDoNothingWithIt) {
        // Should use "if defined" but not sure it works for UDTs...
    }
    ret = s.executeUpdate("create type MUSICRECORDING as object (" + "   id integer," + "   title varchar(20), "
            + "   artist varchar(20) " + ")");
    System.out.println("Created TYPE! Ret=" + ret);

    ret = s.executeUpdate("create table MR of MUSICRECORDING");
    System.out.println("Created TABLE! Ret=" + ret);

    int nRows = s.executeUpdate("insert into MR values(123, 'Greatest Hits', 'Ian')");
    System.out.println("inserted " + nRows + " rows");

    // Put the data class into the connection's Type Map
    // If the data class were not an inner class,
    // this would likely be done with Class.forName(...);
    Map map = con.getTypeMap();
    map.put("MUSICRECORDING", MusicRecording.class);
    con.setTypeMap(map);

    ResultSet rs = s.executeQuery("select * from MR where id = 123");
    //"select musicrecording(id,artist,title) from mr");
    rs.next();
    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
        Object o = rs.getObject(i);
        System.out.print(o + "(Type " + o.getClass().getName() + ")\t");
    }
    System.out.println();
}

From source file:Main.java

public static void main(String[] argv) {
    DefaultTableModel model = new DefaultTableModel() {
        public Class getColumnClass(int mColIndex) {
            int rowIndex = 0;
            Object o = getValueAt(rowIndex, mColIndex);
            if (o == null) {
                return Object.class;
            } else {
                return o.getClass();
            }/*from w ww .ja  v  a2 s .co  m*/
        }
    };
    JTable table = new JTable(model);
    model.addColumn("Col1", new Object[] { Color.red });
    model.addRow(new Object[] { Color.green });
    model.addRow(new Object[] { Color.blue });

    table.setDefaultRenderer(Color.class, new ColorTableCellRenderer());

    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.add(new JScrollPane(table));
    f.setVisible(true);
}

From source file:com.nabla.project.application.tool.runner.ServiceRunner.java

/**
 * DOCUMENT ME!//from   ww w. j a  va 2 s.  c  om
 * 
 * @param args DOCUMENT ME!
 * @throws Exception DOCUMENT ME!
 * @throws RuntimeException DOCUMENT ME!
 */
public static void main(String args[]) throws Exception {

    ObjectInputStream ois = new ObjectInputStream(System.in);
    Object methodArgs[] = (Object[]) ois.readObject();

    if (args.length < 3) {

        throw new RuntimeException(
                "Error : usage : java com.nabla.project.application.tool.runner.ServiceRunner configFileName beanName methodName");

    }

    String configFileName = args[0];
    String beanName = args[1];
    String methodName = args[2];
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { configFileName });
    Object service = context.getBean(beanName);
    Method serviceMethod = null;
    Method methods[] = service.getClass().getMethods();

    for (Method method : methods) {

        if (method.getName().equals(methodName)) {

            serviceMethod = method;

        }

    }

    if (serviceMethod == null) {

        throw new RuntimeException("Method " + methodName + " not found in class " + service.getClass());

    }

    serviceMethod.invoke(service, methodArgs);

}

From source file:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;/*from w ww  .j a  v a  2s .c o  m*/
    try {
        url = new URL("http://198.11.209.34:5000/v2.0/tokens");
    } catch (MalformedURLException ex) {
        System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0");
        return;
    }
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity strEntity = new StringEntity(
                "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}");
        httpPost.setEntity(strEntity);
        //System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            //get the response status code 
            String respStatus = response.getStatusLine().getReasonPhrase();

            //get the response body
            int bytes = response.getEntity().getContent().available();
            InputStream body = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(body));
            String line;
            StringBuffer sbJSON = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sbJSON.append(line);
            }
            String json = sbJSON.toString();
            EntityUtils.consume(response.getEntity());

            GsonBuilder gsonBuilder = new GsonBuilder();
            Object parsedJson = gsonBuilder.create().fromJson(json, Object.class);
            System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString());
            if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) {
                com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson;
                if (treeJson.containsKey("id")) {
                    String s = (String) treeJson.getOrDefault("id", "no key provided");
                    System.out.printf("\n\ntree contained id %s\n", s);
                } else {
                    System.out.printf("\n\ntree does not contain key id\n");
                }
            }
        } catch (IOException ex) {
            System.out.print(ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        System.out.print(ex);
    } finally {
        //lots of exceptions, just the connection and exit
        try {
            httpclient.close();
        } catch (IOException | NoSuchMethodError ex) {
            System.out.print(ex);
            return;
        }
    }
}

From source file:List.java

public static void main(String[] args) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, "file:/tmp/marketing");

    Object item = null;

    Context initCtx = new InitialContext(env);
    NamingEnumeration nl = initCtx.list("reports");

    if (nl == null)
        System.out.println("\nNo items in name list");
    else/*from ww  w  .  j  av  a  2 s .c o  m*/
        while (nl.hasMore()) {
            item = nl.next();
            System.out.println("item's class is " + item.getClass().getName());
            System.out.println(item);
            System.out.println("");
        }
}

From source file:com.glaf.core.util.JsonUtils.java

public static void main(String[] args) throws Exception {
    Map<String, Object> dataMap = new java.util.HashMap<String, Object>();
    dataMap.put("key01", "");
    dataMap.put("key02", 12345);
    dataMap.put("key03", 789.85D);
    dataMap.put("date", new Date());
    Collection<Object> actorIds = new HashSet<Object>();
    actorIds.add("sales01");
    actorIds.add("sales02");
    actorIds.add("sales03");
    actorIds.add("sales04");
    actorIds.add("sales05");
    dataMap.put("actorIds", actorIds.toArray());
    dataMap.put("x_sale_actor_actorIds", actorIds);

    Map<String, Object> xxxMap = new java.util.HashMap<String, Object>();
    xxxMap.put("0", "--------");
    xxxMap.put("1", "?");
    xxxMap.put("2", "");
    xxxMap.put("3", "");

    dataMap.put("trans", xxxMap);

    String str = JsonUtils.encode(dataMap);
    System.out.println(str);//  w ww. ja v a 2s. c o m
    Map<?, ?> p = JsonUtils.decode(str);
    System.out.println(p);
    System.out.println(p.get("date").getClass().getName());

    String xx = "{name:\"trans\",nodeType:\"select\",children:{\"1\":\"?\",\"3\":\"\",\"2\":\"\",\"0\":\"--------\"}}";
    Map<String, Object> xMap = JsonUtils.decode(xx);
    System.out.println(xMap);
    Set<Entry<String, Object>> entrySet = xMap.entrySet();
    for (Entry<String, Object> entry : entrySet) {
        String key = entry.getKey();
        Object value = entry.getValue();
        System.out.println(key + " = " + value);
        System.out.println(key.getClass().getName() + "  " + value.getClass().getName());
        if (value instanceof JSONObject) {
            JSONObject json = (JSONObject) value;
            Iterator<?> iter = json.keySet().iterator();
            while (iter.hasNext()) {
                String kk = (String) iter.next();
                System.out.println(kk + " = " + json.get(kk));
            }
        }
    }
}

From source file:HasBatteries.java

public static void main(String[] args) {
    Class c = null;//ww  w. ja  v a  2 s . c  o  m
    try {
        c = Class.forName("FancyToy");
    } catch (ClassNotFoundException e) {
        System.out.println("Can't find FancyToy");
        System.exit(1);
    }
    printInfo(c);
    Class[] faces = c.getInterfaces();
    for (int i = 0; i < faces.length; i++)
        printInfo(faces[i]);
    Class cy = c.getSuperclass();
    Object o = null;
    try {
        // Requires default constructor:
        o = cy.newInstance(); // (*1*)
    } catch (InstantiationException e) {
        System.out.println("Cannot instantiate");
        System.exit(1);
    } catch (IllegalAccessException e) {
        System.out.println("Cannot access");
        System.exit(1);
    }
    printInfo(o.getClass());

}

From source file:net.sfr.tv.mom.mgt.HornetqConsole.java

/**
 * @param args the command line arguments
 *///from www.j a va 2 s .c  om
public static void main(String[] args) {

    try {

        String jmxHost = "127.0.0.1";
        String jmxPort = "6001";

        // Process command line arguments
        String arg;
        for (int i = 0; i < args.length; i++) {
            arg = args[i];
            switch (arg) {
            case "-h":
                jmxHost = args[++i];
                break;
            case "-p":
                jmxPort = args[++i];
                break;
            default:
                break;
            }
        }

        // Check for arguments consistency
        if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) {
            LOGGER.info("Usage : ");
            LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n");
            System.exit(1);
        }

        System.out.println(
                SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN)));

        final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':')
                .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort)
                .append("/jmxrmi");

        final String jmxServiceUrl = _url.toString();
        JMXConnector jmxc = null;

        final CommandRouter router = new CommandRouter();

        try {
            jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null);
            assert jmxc != null; // jmxc must be not null
        } catch (final MalformedURLException e) {
            System.out.println(SystemUtils.LINE_SEPARATOR
                    .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED)));
        } catch (Throwable t) {
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED)));
            System.out.print(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA)));
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format(
                    "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?",
                    Color.MAGENTA)));
            System.exit(-1);
        }

        System.out.println("\n".concat(Ansi
                .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW)));

        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // PRINT SERVER STATUS REPORT
        System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null));

        printHelp(router);

        // START COMMAND LINE
        Scanner scanner = new Scanner(System.in);
        System.out.print("> ");
        String input;
        while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) {

            String[] cliArgs = input.split("\\ ");
            CommandHandler handler;

            if (cliArgs.length < 1) {
                System.out.print("> ");
                continue;
            }

            Command cmd = Command.fromString(cliArgs[0]);
            if (cmd == null) {
                System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n"));
                cmd = Command.HELP;
            }

            switch (cmd) {
            case STATUS:
            case LIST:
            case DROP:

                Set<Option> options = router.get(cmd);

                for (Option opt : options) {

                    if (cliArgs[1].equals(opt.toString())) {
                        handler = router.get(cmd, opt);

                        String[] cmdOpts = null;
                        if (cliArgs.length > 2) {
                            cmdOpts = new String[cliArgs.length - 2];
                            for (int i = 0; i < cmdOpts.length; i++) {
                                cmdOpts[i] = cliArgs[2 + i];
                            }
                        }

                        Object result = handler.execute(mbsc, cmdOpts);
                        if (result != null && String.class.isAssignableFrom(result.getClass())) {
                            System.out.print((String) result);
                        }
                        System.out.print("> ");
                    }
                }

                break;

            case FORK:
                // EXECUTE SYSTEM COMMAND
                ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length));
                pb.inheritIO();
                pb.start();
                break;

            case HELP:
                printHelp(router);
                break;
            }
        }
    } catch (MalformedURLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }

    echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN)));

}