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.

Similar Messages

  • Converting String to Calendar Object

    Hi,
    I nedd to Change the below String to Calendar Object.i want to show the records which are older than half an hour.any other idea which will solve my problems?
    Fri Aug 17 01:56:40 GMT+05:30 1906
    Thanks in advance.
    Regards:
    Akash.

    Look at
    java.text.SimpleDataFormat

  • Converting Strings to Color Objects

    Greetings All -
    I'm in my first Java class (I was a C programmer in the 80s!) and am a little stumped on an assigment. Your help will be much appreciated.
    I have to read color strings out of an HTML file and put them in a HashMap (a small applet assignment). I've been unable to find an elegant method for converting from a string to a color object.
    Please let me know if I'm stuck with a big nested if or am I overlooking something?
    Thank you -
    Gargoyle

    This will handle #rrggbb strings, and also the dozen or so colors defined by name (red, cyan, etc) in the static fields of java.awt.Color:
    static Color stringToColor (String s)
         try {
              return Color.decode(s);
         } catch (Exception e) {}
         try {
              return (Color) Color.class.getField(s).get(null);
         } catch (Exception e) {}
         System.out.println("bad color string: " + s);
         return null;
    }

  • Convertion string to Calender object

    The input string format is "hh-mm-ss". How can I convert to Calender object.
    Can anybody suggest ?
    Thanks
    Pravat

    Use a java.text.SimpleDateFormat to convert the string to a java.util.Date object and then set the calendar object from that.

  • Issue with converting string to date object

    Hi all,
    I have a problem with sorting a list of dates in a table column. My dates are in the format 'yyyy-Mmm-dd'(Eg: 2009-Dec-23). Can someone help me how to sort the dates in this format. here is the code which i tried.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-Mmm-dd");
              Date d1= new Date();
              Date d2= new Date();
              try {
                   d1 = dateFormat.parse("2006-Jun-09");
                 d2 = dateFormat.parse("2006-Apr-10");
              } catch (ParseException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              System.out.println("converted date 1"+ d1);
             System.out.println("converted date 1"+ d2);
    Exception : Unparseable date: "2006-Jun-09"
         }Please someone help me how to pass this date in the right format.

    I believe twisai may have lost the documentation so he/she can figure this out rather than guess that "Mmm" means 3-letter month, first letter capitalized. Let me remind him of the link:
    [http://java.sun.com/javase/6/docs/api/index.html]

  • How can I convert a string to an object or class

    I would like to read a file representing a class, and convert it to an object or a class (object preferred). Other postings suggest using javax.tools.JavaCompiler to convert from a string but then say that this is not always available (posting on 1 Jan 09). If this is still not universally available is there another way to do this? If this is not available, are there any examples of how it should be done?
    My understanding from what I've read is to read the file into a String then compile the String using javax.tools.JavaCompiler, which is an Interface.
    thanks

    skidmarks wrote:
    What i would like to do is to take a Java file representing a class and compile it at runtime. However, the comment about a JDK being available at runtime makes this unattractive.So, you want to compile .java files, but you don't want to have to use a compiler?
    The next guess would to be to create a .jar file and reference it at runtime. Here's the scenario:Eh? How is that even remotely equivalent?
    1. People using the 'system' will have a varied knowledge of Java.
    2. My hope was to require that anyone using the program would only need to create a Java Class file,You mean a Java source file. You have said that YOU want to create the .class file. If they are creating the .class file, then all you need to do is load it with a ClassLoader and start using it.
    You might try clarifying your requirements a bit.
    In either case, the Class Files would look like:
    public class Name {
    int field1;
    float field2;
    } With all the field types being simple Java Primitives.What is the point of this? What are you ultimately trying to accomplish, that can be served by user-defined groups of primitives, with no complex object graphs and no user-defined methods?
    Depending on what you're really getting at, using scripting features via beanshell, groovy, or javascript might be an approach to consider, or using Scala to produce a domain-specific language (although I suspect that last may be overkill, and beyond your current skill level).
    If this is so, is there any way to create a .jar file at runtime? Do I have to exec("jar") or is there another way.A .jar file is just a .zip file with a manifest. Look at the java.util.jar package. But note that creating a .jar file has nothing to do with the rest of what you're asking about.

  • String to xml object java

    Hello,
    can anyone suggest me how to convert string to xml object in java?
    I have a string (Data) ant now I have to pass it as parameter as xml object, which structure should be:
    <MGWData>Data</MGWData>
    Where I surf I always see only solutions for converting string to xml document, but never to xml object.
    maybe the problem is I don't completely understand what xml object is in first place :/
    Any answer would help.
    Thanks.

    894871 wrote:
    here is the method to call:
    +/**+
    * Sets the p_DATAXMLTYPEIN value for this SVARCHAR2INSERT_RECEIVESInput.
    *+
    * @param p_DATAXMLTYPEIN
    *public void setP_DATAXMLTYPEIN(com.oracle.xmlns.orawsv.SISTEMA_MOKA.MGW_PUBLIC_FUNCTIONS.SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN p_DATAXMLTYPEIN) {*
    this.p_DATAXMLTYPEIN = p_DATAXMLTYPEIN;
    one of the classes contains:
    *public class SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN  implements java.io.Serializable, org.apache.axis.encoding.AnyContentType {*
    *private org.apache.axis.message.MessageElement [] _any;*
    this method and some classes where generated using eclipse and wsdl file by creating web service client.
    wsdl says for that part: *<xsd:element name="P_DATA-XMLTYPE-IN">*
    So I suppose it should involve smth org.apache.axis.message.MessageElement. But when I create any type of parameter, it gives me error:
    + ....cannot be cast to com.oracle.xmlns.orawsv.SISTEMA_MOKA.MGW_PUBLIC_FUNCTIONS.SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN+
    I am new in web service stuff so thank you for response.Can you explain in plain English what you are trying to do? Or provide a [url http://sscce.org/]SSCE.

  • Convert String variable value  to an Object referece type

    Hi all,
    I want to know that if there any possible way to convert String variable value to a Object reference type in java. I'll explain by example if this is not clear.
    Let's think that there is a string variable name like,
    String name="HelloWorld";
    and there is a class name same to the variable value.
    class HelloWorld
    I am passing this string variable value to a method which is going to make a object of helloworld;
    new convertobj().convert("HelloWorld");
    class convertobj{
    public void convert(String name){
    // in hert it is going to create the object of HelloWorld;
    // HelloWorld hello=new HelloWorld(); just like this.
    now i want to do this from the name variable value.( name na=new name()) like wise.
    please let me know if there any possible way to do that.
    I am just passing the name of class by string variable then i wanted to make a instance of the class which come through the variable value.
    thanx.

    Either cast the object to a HelloWorld or use the reflection API (Google it) - with the reflection API you can discover what methods are available.
    Note: if you are planning to pass in various string arguments and instantiate a class which you expect to have a certain method... you should define an interface and have all of your classes that you will call in this way implement the interface (that way you're sure the class has a method of that name). You can then just cast the object to the interface type and call the method.
    John

  • How to convert a string to date object?

    I have a string user input for date.
    I want to convert it to Date object to insert it in database.
    How to do it?

    Check the java.text.SimpleDateFormat class. You can use it for parsing dates. API contains good description how to build the format pattern.
    HTH
    Mike

  • Converting String to Class?

    I'm trying to convert a String to a Class name and then instantiate an object from that class. It's proving to be quite difficult. I have a Query object which is a superclass and has several subclasses, one of which is CommonQuery. Here's my code so far. Basically I need "c" to be the specific type of Query that it should be. What am I doing wrong?
    for(Query q:results)
                Class cl = Class.forName(myClass);//myClass is the String that I'd like to convert to a class, CommonQuery for example
                Constructor ct = cl.getConstructor(new Class[]{Query.class});//Query is the superclass but they all have the same constructor
                Query c = (Query)(ct.newInstance(new Object[]{q.getWords(),q.getFile()}));
                c.computeRank();
                unsorted.add(c);
    }

    This is the error that I'm getting:
    Exception in thread "main" java.lang.NoSuchMethodException: nano.CommonQuery.<init>(nano.Query)
         at java.lang.Class.getConstructor0(Unknown Source)
         at java.lang.Class.getConstructor(Unknown Source)I guess this is what you meant about not overriding the constructors. How do I get the constructor from a class that I don't know what it is yet?
    What goes in here where I have Query.class?
    Constructor ct = cl.getConstructor(new Class[]{Query.class});I'm not familiar with the reflection forums. Should I go post in there now?

  • Converting a String to an Object

    Is there some way of converting a String (from a textfield) to an Object? What I want is something similar to the functionality offerred by a JTable. This is because I want the user to be able to input a value of any type to the textfield (e.g. String, int, boolean, etc) and get its object representation ...
    Would a simple cast do ?
    David

    dattard,
    A string is an object, when someone enters something into a JTextField, REGARDLESS of what it is (int, double, string, etc) it is stored in the string text in that text field (JTextField.getText()).
    So if someone enters in "123", its the STRING 123, not the number one hundred and twenty three... to GET the number 123, you'll need to do something like:
    int value = Integer.parseInt( myTextField.getText() );
    to have the string parsed for the value, if you want a double, same idea:
    double value = Double.parseDouble( myTextField.getText() );
    NOTE: The number wrapper classes (Integer, Double, Float, etc.) contain "parseXXXX" methods that allow you to parse a corresponding numeric value out of a String object.
    Also, when a user enters ANYTHING into a text input field of any type, its ALWAYS a String, if you want a different version of what they entered, its up to you to parse it and decide what it was.

  • 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); }

  • Convert strings to publicKey/privateKey objects

    Hi,
    I have the following problem : I'm generating RSA key pairs in string formats. I want to sign an XML document so I have to specifiy KeyPair object in order to do that.
    How can I convert string to publicKey and privateKey objects ?
    i.e How can I correct this code :
    String pubKey = generatePublicKey();
    String priKey = generatePrivateKey();
    KeyPair kp = new KeyPair(pubKey,priKey);
    // sign the XML documents
    Thanks a lot for your precious help.
    Cheers,
    Othman.

    http://forum.java.sun.com/thread.jspa?threadID=577716&tstart=0

  • 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)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Converting String to ISO-8859-1 html charset

    i want to convert string to ISO-8859-1 html charset or vice versa
    For example i need to replace "ö" as  "&#246;"
    How can i do that?
    http://www.unicodetools.com/unicode/utf8-to-latin-converter.php

    i want to convert string to ISO-8859-1 html charset or vice versa
    For example i need to replace "ö" as  "&#246;"
    How can i do that?
    http://www.unicodetools.com/unicode/utf8-to-latin-converter.php
    This seems to return #246; but not &#246; for ö. Unless the & character is not getting displayed for some reason.
    HttpUtility.HtmlEncode Method (String)
    HttpUtility.HtmlDecode Method (String, TextWriter)
    Option Strict On
    Imports System.Web
    Imports System.IO
    Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.Text = "Form1"
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim myString As String = "ö"
    Dim myEncodedString As String = HttpUtility.HtmlEncode(myString)
    Label1.Text = " " & myEncodedString & " "
    Dim myWriter As New StringWriter()
    HttpUtility.HtmlDecode(myEncodedString, myWriter)
    Label1.Text &= myWriter.ToString
    End Sub
    End Class
    La vida loca

Maybe you are looking for

  • How to Print Post Script Files

    Hi All, I am trying to make a utility software in foxpro that could print post script file on:- 1) Post script printer 2) Non Post Script printer Operating System Windows 95 & above Help is requested from all the community members Reagards Harsh

  • After installing iOS 5.1 I can no longer call people with Siri without unlocking the phone

    Is this an intended change of behavior?  How can I get this functionality back?  I was using it all the time.  Now I have to dig my phone out of my pocket and unlock it to make a call even if I am using a handsfree headset. 

  • Creating a hyperlink to an IM

    Hi all, I am curious to know if anyone is aware of a method to launch an instant message when a user clicks on an image within a site. The site is for internal use and we are all on MS Lync. The link is similar to an email link 'mailto:[email protect

  • Web to PDF - Convert to PDF/X-3 (Error: file specifications present)

    I took a simple webpage consisting of two images and some text and used the Adobe Acrobat X Pro function "PDF to Web" to make a pdf of it, which looks perfectly good. I need to export it as a PDX/X-3 compliant pdf however in preflight I get the error

  • Materialised Views

    Oracle Version 9.2.0.2 I'm trying to improve what is currently terrible performance with BI Beans!! I have 1 fact table with 3 dimensions, and 1 hierarchy, stored in a simple star schema. I've defined my metatdata using OEM. Reading the 9i OLAP Users