Making Strings an object of a class

Okay hello. Now i have LinkedList<Customer> customers = new LinkedList<Customer>();now i am trying to add a string into this list. i know this is not possible as the list that i made is of type object.
My question is how do i make a string into an object so that it can be added into the list.
String l = (Customer) x;i know this is wrong that is why i am asking how do i make the string so that it can be added into the list of customers. Customer is a class. Does the conversion of String to Customer object meant to be done in that class?? please help

That String is an input. Thats the problem im having. As it is a string that im inputing the customers.add(l) doesnt work. for example, foreget the String l = (Customer) x. We have concluded this doesnt work. But when i do String l, the cusomters.add(l) comes up with an error. The error is it cannot find add(). This way the add() is just some ordinary one and not of the Liked List type. Therefore simple putting String l; is inefficient for the list to work, thus i need to make a parser so that the String becomes of type Customer. But i do not know how to make the parser, or even where to start. I have seen one that made double into string, but not object to string. are the ways these 2 are done similar?
import java.io.*;
import java.util.*;
public class Customers implements Serializable
{   private LinkedList<Customer> customers = new LinkedList<Customer>();
    Customer x;
    String z;
    double y;
    String l;
    public void add()
    {   System.out.println("Add a customer");
        l = Store.nextLine();
        customers.add(l); }

Similar Messages

  • Converting String to an Object of a class

    Hi all,
    I want to convert a string to an object of a class.
    Please see my below code:
    MyClass rahul = null;
    String data = "DATA";
    rahul = (MyClass) data;
    I am getting the error: Invalid cast from java.lang.String to MyClass
    Please help me as its urgent

    There is no magical String deserialization in java. If your class can convert it's state to a string, then you will need to write the reverse parsing code, presumably using either a constructor which takes a string, or a static method similar to how numbers are handled, like:
    MyClass c = MyClass.valueOf(data);Obviously, in either case you will need to write the code to do this.

  • How do i create objects of ordinary Classes from a javabean

    I want to create a class Person below that I want to create an object from in my javabeans.
    Look below Person class definition for continuation.
    package data;
    public class Person
    private String name;
    public Person()
    name = "No name yet.";
    public Person(String initialName)
    name = initialName;
    public void setName(String newName)
    name = newName;
    public String getName()
    return name;
    public void writeOutput()
    System.out.println("Name: " + name);
    public boolean sameName(Person otherPerson)
    return (this.name.equalsIgnoreCase(otherPerson.name));
    I run this bean class in the WEB-INF/classes/data folder creating a Person object in the deal() method below
    When I compile the class it seems to fail. It does not recognise the Person class. Can you help me with a description of what to do to call
    ordinary class objects from javabean class definitions.
    What directories should the simple classes be put and what should I include in the javabean to be able to access them?
    package data;
    import java.sql.*;
    import data.*;
    public class Bean
    { private Connection databaseConnection ;
    // private Person p;
    public Bean()
    super();
    public boolean connect() throws ClassNotFoundException, SQLException
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String sourceURL = "jdbc:odbc:robjsp";
    databaseConnection = DriverManager.getConnection(sourceURL);
    return true;
    public ResultSet execquery(String restrict) throws SQLException
    Statement statement = databaseConnection.createStatement();
    String full = "SELECT customerid,CITY,Address from customers " + restrict;
    ResultSet authorNames = statement.executeQuery(full);
    return (authorNames ==null ) ? null : authorNames;
    public String deal() throws SQLException
    {  Person p = new Person();
    p.setName("Roberto");
    return p.getName();
    }

    There is no "Copy File" function in Lightroom.
    Lightroom was designed to eliminate the need to make duplicate copies of files. The organizational tools in Lightroom allow you to have one file categorized in many ways, you can assign multiple keywords to the photos (for example: Winery, Finger Lakes, Fall Foliage, Jessica). Similarly, you can have a file categorized in multiple Lightroom collections at the same time, all without making a copy of the photo. The benefit of this is that you don't need to make multiple copies of each photo, one copy suffices, and thus disk space is saved; and furthermore if you should edit a photo or add metadata, you only need to do this once, and the photo's appearance, or the photo's metadata is changed, and visible to you no matter how you choose to access the photo (pick any keyword or any collection and you will see the change)

  • Accessing the same object from multiple classes.

    For the life of me I can't workout how I can access things from classes that haven't created them.
    I don't want to have to use "new" multiple times in seperate classes as that would erase manipulated values.
    I want to be able to access and manipulate an array of objects from multiple classes without resetting the array object values. How do I create a new object then be able to use it from all classes rather than re-creating it?
    Also I need my GUI to recognize the changes my buttons are making to data and reload itself so they show up.
    All help is good help!
    regards,
    Luke Grainger

    As long as you have a headquarters it shouldn't be to painfull. You simply keep a refrence to your ShipDataBase and Arsenal and all your irrellevant stuff in Headquarters. So the start of your Headquarters class would look something like:
    public class Headquarters{
      public Arsenal arsenal;
      public ShipDatabase db;
    //constructor
      public Headquarters(){
        arsenal = new Arsenal(this, ....);
        db = new ShipDatabase(...);
    //The Arsenal class:
    public class Arsenal{
      public Headquarter hq;
      public Arsenal(Headquarter hq, ....){
        this.hq = hq;
        .Then in your ShipDatabase you should, as good programing goes, keep the arraylist as a private class variable, and then make simple public methods to access it. Methods like getShipList(), addToShipList(Ship ship)....
    So when you want to add a ship from arsenal you write:
    hq.db.addToShipList(ship);
    .Or you could of course use a more direct refrence:
    ShipDatabase db = hq.db;
    or even
    ShipList = hq.db.getShipList();
    but this requires that the shiplist in the DB is kept public....
    Hope it was comprehensive enough, and that I answered what you where wondering.
    Sjur
    PS: Initialise the array is what you do right here:
    //constructor
    shipList = new Ship[6];
    shipList[0] = new Ship("Sentry", 15, 10, "Scout");
    " " " "etc
    shipList[5] = new Ship("Sentry", 15, 10, "Scout");PPS: To make code snippets etc. more readable please read this article:
    http://forum.java.sun.com/faq.jsp#messageformat

  • Casting base class object to derived class object

    interface myinterface
         void fun1();
    class Base implements myinterface
         public void fun1()
    class Derived extends Base
    public class File1
         public myinterface fun()
              return (myinterface) new Base();
         public static void main(String args[])
              File1 obj = new File1();
              Derived dobj = (Derived)obj.fun();
    Giving the exception ClassCastException......
    Can't we convert from base class object to derived class.
    Can any one help me please...
    Thnaks in Advance
    Bharath kumar.

    When posting code, please use tags
    The object returned by File1.fun() is of type Base. You cannot cast an object to something it isn't - in this case, Base isn't Dervied. If you added some member variables to Derived, and the compiler allowed your cast from Base to Derived to succeed, where would these member variables come from?
    Also, you don't need the cast to myinterface in File1.fun()
    Also, normal Java coding conventions recommend naming classes and interfaces (in this case, myinterface) with leading capital letters, and camel-case caps throughout (e.g. MyInterface)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Why can't I create new object from a class that is in my big class?

    I mean:
    class A
    B x = new B;
    class B
    and how can I solve it if I still want to create an object from B class.
    Thank you very much :)

    public class ItWorksNow  {
      public ItWorksNow() {
      public static void main ( String[] argv )  throws Exception {
        ItWorksNow.DaInnaClass id = new ItWorksNow().new DaInnaClass();
      public class DaInnaClass {
    }

  • Get session object in a class

    hi,
    is possible obtain the session object in a class method without send it from jsp as a parameter?

    you mean like this?
         public ActionForward execute(
              ActionMapping mapping,
              ActionForm form,
              HttpServletRequest req,
              HttpServletResponse res)
              throws Exception {
              SessionManager sm = new SessionManager(req);
                                    ....sessionmanager class
    package com....;
    import java.util.*;
    import java.lang.reflect.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.jsp.*;
    import javax.servlet.http.*;
    import org.apache.log4j.*;
    * <code>SessionManager</code> is a wrapper for request, response and session
    * @author
    public class SessionManager {
         static Logger log = Logger.getLogger(SessionManager.class);
         ** Holds string containing the unique identifier assigned to this session
         private String sessionid;
         ** Holds HttpSession object
         private HttpSession session;
         ** Holds request object object - must be passed in by the calling application
         private HttpServletRequest request;
         ** Holds response object - any application sending a response must call
         ** session manager
         private HttpServletResponse response;
         ** Holds Servlet Context - useful if logging is reqd.
         private ServletContext context;
          * Page context.
         private PageContext pctx = null;
         ** Constructor to initialize with a request object
         public SessionManager(HttpServletRequest req) {
              request = req;
              session = req.getSession();
              sessionid = session.getId();
         ** Constructor to initialize with a pagecontext object - convenient to call from jsp's
         public SessionManager(PageContext pctx) {
              request = (HttpServletRequest) pctx.getRequest();
              response = (HttpServletResponse) pctx.getResponse();
              context = pctx.getServletContext();
              session = pctx.getSession();
              sessionid = session.getId();
              this.pctx = pctx;
         ** Constructor to initialize with request, response objects
         public SessionManager(HttpServletRequest req, HttpServletResponse resp) {
              request = req;
              response = resp;
              session = req.getSession();
              sessionid = session.getId();
         ** Constructor to initialize with request, servletcontext objects
         public SessionManager(HttpServletRequest req, ServletContext ctx) {
              request = req;
              context = ctx;
              session = req.getSession();
              sessionid = session.getId();
         ** Constructor to initialize with request, response and context objects
         public SessionManager(HttpServletRequest req, HttpServletResponse resp, ServletContext ctx) {
              request = req;
              response = resp;
              context = ctx;
              session = req.getSession();
              sessionid = session.getId();
         ** Setter and getter methods
         public void setRequest(HttpServletRequest req) {
              request = req;
              session = req.getSession();
              sessionid = session.getId();
         ** Setter and getter methods
         public void setContext(ServletContext ctx) {
              context = ctx;
         ** Setter and getter methods
         public ServletContext getContext() {
              return context;
         public void createLoginSession(java.io.Serializable obj) {
              if (obj == null)
                   log.debug("Object is null");
              setAttribute("user", obj);
         public void setAttribute(String key, java.io.Serializable obj) {
              session.setAttribute(key, obj);
         public void removeAttribute(String key) {
              session.removeAttribute(key);
         ** Setter and getter methods
         public HttpServletRequest getRequest() {
              return request;
         ** Setter and getter methods
         public HttpServletResponse getResponse() {
              return response;
         ** Checks if either member session or guest session exists
         public boolean isLoggedIn() {
              if (session.getAttribute("user") != null)
                   return true;
              else
                   return false;
         public long getCreationTime() {
              return session.getCreationTime();
         ** Setter and getter methods
         public String getId() {
              return session.getId();
         public long getLastAccessedTime() {
              return session.getLastAccessedTime();
         public int getMaxInactiveInterval() {
              return session.getMaxInactiveInterval();
         ** Setter and getter methods - also useful for retrieving state object(s)
         public Object getAttribute(String name) {
              if (session != null)
                   Object sObject = session.getAttribute(name);
                   //Log.debug("Session State for the object "+name+" is "+sObject);
                   return sObject;
              else
                   return null;
         ** Setter and getter methods - gets enum of all stored state objects
         public Enumeration getAttributeNames() {
              return session.getAttributeNames();
         public void invalidate() {
              session.invalidate();
              // Remove all object that is bound to this session
              //wip : Resetting instance variable.
              //This is necesary as further operations on session will
              //result in illegalstateexception
              session = null;
         public boolean isNew() {
              return session.isNew();
         public void setMaxInactiveInterval(int interval) {
              session.setMaxInactiveInterval(interval);
          * This method returns the host url in the form "www.carclub.com".
          * <p>
          * The return value is compatible with default_website field of clubs DB table.
          * </p>
          * @return host url present as part of the http request object
         public String getHostURL()
              if (request == null)
                   return null;//No request object present, hence return null
              String str = request.getServerName();
              //Log.debug("--- The request URL is --- " + str);
              return str;
          * Flushes <code>out</code> stream.
         public void flush()
              throws IOException
              if (pctx != null)
                   pctx.getOut().flush();
    }

  • Instantiating an object of a class using variable

    Can anyone please tell me how to instantiate an object of a class, the class name is stored in string variable.
    something like:
    String s = "MyClass";
    <s> anObj = new <s> ;
    what will be the appropriate substitution of <s> ?

    Orkay, Leave it up to u to learn the Exceptions that are gonna be thrown. Look up the APIs, Rather easy
    String s = <fullyQualifiedClassName>;
    try {
      Class someClass = Class.forName(s);
      Object instance = someClass.newInstance();
      if (instance instanceof <someExpectedInstance>) {
        <someExpectedInstance> x = (<someExpectedInstance>) instance;
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }Primarily look up the reflection API, and in particular Class.

  • Referencing fields between objects of same class

    Say I have created multiple TicketMachines from this class. Is there a way I create a method that uses "System.out.println" that would print the price of another TicketMachine object. And if so, could you please point me in the direction to find out how.
    * TicketMachine models a naive ticket machine that issues
    * flat-fare tickets.
    * The price of a ticket is specified via the constructor.
    * It is a naive machine in the sense that it trusts its users
    * to insert enough money before trying to print a ticket.
    * It also assumes that users enter sensible amounts.
    * @author David J. Barnes and Michael Kolling
    * @version 2006.03.30
    public class TicketMachine
        // The price of a ticket from this machine.
        private int price;
        // The amount of money entered by a customer so far.
        private int balance;
        // The total amount of money collected by this machine.
        private int total;
        //Creates a machine that issues tickets at a default price of 1000.
        public TicketMachine( )
         //Exercise 2.39  & 2.42(continues below)
          * By removing the parameter from this constructer
          * and setting the value of price to 1000, objects
          * from this class are automatically constructed with
          * a ticket price of 1000.
            price = 1000;
            balance = 0;
            total = 0;
        //Exercise 2.42
         * Create a machine that issues tickets of the given price.
         * Note that the price must be greater than zero, and there
         * are no checks to ensure this.
        public TicketMachine(int thePrice)
            price = thePrice;
            balance = 0;
            total = 0;
         * Return the price of a ticket.
        public int getPrice()
            return price;
         * Return the amount of money already inserted for the
         * next ticket.
        public int getBalance()
            return balance;
         * Receive an amount of money in cents from a customer.
        public void insertMoney(int amount)
            balance = balance + amount;
         * Print a ticket.
         * Update the total collected and
         * reduce the balance to zero.
        public void printTicket()
            // Simulate the printing of a ticket.
            System.out.println("##################");
            System.out.println("# The BlueJ Line");
            System.out.println("# Ticket");
            System.out.println("# " + price + " cents.");
            System.out.println("##################");
            System.out.println();
            // Update the total collected with the balance.
            total = total + balance;
            // Clear the balance.
            balance = 0;
        //Exercise 2.33
        //Prints "Please insert the correct amount of money." to the text terminal.
        public void prompt()
            System.out.println("Please insert the correct amount of money.");
        //Exercise 2.34
        //Displays the value of the price field in the text terminal.
        public void showPrice()
            System.out.println("The price of a ticket is " + price + " cents.");
        //Exercise 2.35
         * After creating two ticket machines with different prices
         * and calling thier showPrice methods it showed a different
         * output for each instance. This effect happenes because the
         * showPrice method prints out a string and the value of the price
         * field, which happens to be different in each instance, thereby
         * printing a different output.
        //Exercise 2.36
         * The result of System.out.println("# " + "price" + " cents.");
         * would print the string "# price cents." to the text terminal.
        //Exercise 2.37
         * The result of System.out.println("# price cents.");
         * would be the same as the result of exercise 2.36.
        //Exercise 2.40
        //This method is a mutator and takes no parameters
        //Empties the money form the ticket machine
        public void empty()
            total = 0;
        //Exercise 2.41
        //This method is a mutator
        //Changes the price of a ticket
        public void setPrice(int newPrice)
            price = newPrice;
    }

    Objects can refer to fields in other objects of the same class.
    It's not clear from your description what you're trying to accomplish, however.

  • How to create an object of a class?

    plz read the question carefully ..
    how to create the object of a class by giving the class name as an String
    suppose i have a java file name:" java1.java ".
    so now how to create an object of this class "java1"by passing a string "java1"..

    kajbj wrote:
    rajeev-usendi wrote:
    thanks but still i have problem..
    i have created the object but now i m unable to do anything with that created object..
    i have coded like this..
    Object o= Class.forName("java1").new Instance();
    after this i m unable to do anything with the object 'o'..So why did you create the instance? You can also get all methods using reflection, but that is probably not what you want to do. You should instead let the class implement an interface and cast the created object into that interface ans call the methods that you want to call.
    KajI agree with Kaj. If you need to use a class that's unavailable at compile time, you should create an appropriate interface by which to refer to the class and then you create instances reflectively and access them normally via their interface (which is called reflective instantiation with interface access)

  • How to create object by getting class name as input

    hi
    i need to create object for the existing classes by getting class name as input from the user at run time.
    how can i do it.
    for exapmle ExpnEvaluation is a class, i will get this class name as input and store it in a string
    String classname = "ExpnEvaluation";
    now how can i create object for the class ExpnEvaluation by using the string classname in which the class name is storted
    Thanks in advance

    i think we have to cast it, can u help me how to cast
    the obj to the classname that i get as inputThat's exactly the point why you shouldn't be doing this. You can't have a dynamic cast at compile time already. It doesn't make sense. Which is also the reason why class.forName().newInstance() is a very nice but also often very useless tool, unless the classes loaded all share a mutual interface.

  • How to make an object of inner class and use it ?

    Hi tecs,
    In my JSF application i have a need to make an inner member class in one of my bean class.
    How can i make the object of this class?(what should be the entry in faces-config)
    And there are text box and check box (in the JSP) associated with the elements of this inner class. What should be the coding in JSP so that elements in the JSP can be linked with the corresponding members of the inner class ?
    Plz help.
    Thnx in advance.

    Hi
    I am havin 10 text boxes in my application.
    But out of 10 , 3 will be always together(existence of one is not possible without the other two.)
    Now i want to create a vector of objects ( here object will consist of the value corresponding to these three boxes),there can be many elements in this vector.
    So i m thinking to make an inner class which have three String variables corresponding to these text boxes that exists together.
    What can b done ?

  • Is it possible in an html to call the objects of a class?

    Hi,
    Please help me.I have already posted it, but it's very urgent i am in need for an working answer.
    I am calling an applet class 2 times in a browser.To share some variable i have declared as private static. But when i call these applets are called in different browsers , still these variables are shared.
    Actually i want the applets in one browser to be independent of the other applets in a separate browser. Can anyone help me to solve this problem?
    Is it possible in an html to call the objects of a class?
    Is there any some workarounds? For instance calling applets in separate JVM in the same machine.Any idea how to do that?
    Another option is using something like the session variables. But is that possible in a variable inside the applet class?
    Thanks in advance to all the solutions. Hope someone clicks an idea from the above possibilities.

    To get a reference to other applets in the same JVM (actually same browser window), do the following:
    //get a reference to the other applets in the same browser window
    java.applet.AppletContext appCon = yourAppletRef.getAppletContext();
    JApplet applet = (JApplet) appCon.getApplet(otherAppletName);or use AppletContext.getApplets() to get an enumeration of all the accessible applets. If you want to use the Session object to store your values, then, in your javascript, make a call to the applet methods. Use JSP expressions for the value of these session String values (i.e. <%= %>) to set the parameters of your applet methods. In a nutshell, it is possible. I hope this helps.

  • Create Object of "ObjectName" Class by giving only Domain Name.

    Hie,
    I want to create Object of "ObjectName" class without specifying its key value properties, but i want to only specify the domain name.
    For eg:
    ObjectName on=new ObjectName("jboss.ws4ee:*"); here jboss.ws4ee is the domain name and after colon(:) will come the key value properties.. i dont want to specify that because i want the list of all mbeans coming under this domain i.e. jboss.ws4ee
    So anyone can plzzz help me..
    Regards.

    Hi,
    What were you trying to do with that name?
    ObjectName on=new ObjectName("jboss.ws4ee:*");
    You cannot create an MBean with such an ObjectName. You can only
    use it as first argument to queryNames() and queryMBeans();
    If you want to get the attributes of all jboss MBeans then you will need to
    do something like that:
    final ObjectName pattern=new ObjectName("jboss.ws4ee:*");
    for (ObjectName o : server.queryNames(pattern,null)) {
        System.out.println("MBean:  " + o);
        for (MBeanAttributeInfo info : server.getMBeanInfo(o).getAttributes()) {
             final String attrname = info.getName();
             System.out.println("\t"+attrname+"="+server.getAttribute(o,attrname));
    }(disclaimer: this code was eyed-compiled)
    hope this helps,
    -- daniel
    JMX, SNMP, Java, etc...
    http://blogs.sun.com/jmxetc

  • Java Core Program :: Dynamic Object Creation for Classe & Invoking the same

    Hi,
    I need to create a dynamic object for a class & invoke it.
    For eg: I have a table in my DB where all the names of my java classes are stored. I need to call name from the table of the DB and call that class dynamically in my java program.
    ResultSet_01 = executeQuery("select classname from class_table where class_descrip = 'Sales Invoice' ");
                   while(ResultSet_01.next())
                        String class_name = ResultSet_01.getDouble("classname");
                   }Now using the string in class_name that is fetched from ResultSet_01, I need to create an object for the class_name & invoke the class that is been created with the same name.
    Thank in advance.
    Regards,
    Haider Imani

    Well for a start since a class name is a String, not a number you'd better start by getting the name with getString() not getDouble().
    You need to work with fully qualified names, (FQNs) like "com.acme.myproject.MyDynamicClass", not just the bare MyDynamicClass.
    The next question is where the .class files for the dynamically loaded classes are stored. If they are part of your normal program code, on the class path, then you can use Class.forName to load the class and return a Class object. If they are in some special place you'll need to create a URLClassLoader and get the Class from that.
    Generally, when you load a class this way, it should implement some known interface, or extend some know abstract class. By placing objects of the dynamic class in a reference to that interface you can use the methods defined in the interface.
    The usual way of getting an instance of a dynamic class is to call newInstance() on the Class object.

Maybe you are looking for

  • Windows 7 on external drive

    Hey all, I want to have a copy of Windows 7 available for rare use. I don't want to have a Bootcamp partition on my hard drive. Is it possible to have Bootcamp on an external drive? I want to use a flash drive. I tried using WinClone and found out th

  • Mass Upload of BP Data

    Hi Experts, I have been tasked with looking at options to Upload 1,6 Million BP records into a Standalone SAP CRM Box. Business has decided that only BP Address data needs to be bought across from our ISU box. As I am not a Migration consultant, I am

  • HT1923 why is itunes not installing correctly. keep getting error 7

    I keep getting a message saying something about my apple mobile device (error 7) when I am trying to install itunes on my laptop

  • Can't print in Landscape mode since installing Snow Leopard

    Since the installation of Snow Leopard 10.6.2 I can't print in landscape format from application such as Word, powerpoint, Turbo Cad, etc, on my network printer. This is despite changing my page set-up and printer settings My only work around at the

  • Fireworks loses filename when opening

    I recently updated my Fireworks CS5. I'm not sure which build i'm on because the About will not open anymore. My main issue is when I open a saved file inside of Fireworks, it acts like its a new page and doesn't keep the filename. So everytime I sav