String to object?

Hi,
I have a problem in converting string to object.
The way I intended to do is like this:
String a1 = "John";
String a2 = "Smilth";
String a3 = "Eric";
String a10 = "Howard";
and I wanna assgin the value of a1 ~ a10 into a temp string.
like this;
for (int i = 1; i<= 10; i++)
String tempString = "a" + i; //assign the value of original string into tempString.
// bla bla bla
I know I have to use class.forName() to get what I want, but I have no clue on how to
implement this in detail. Any help will be great appreciated.
Thanks
TC Wang

May I ask why you do it so complicatec? Why don't you use an array?
String[] a = new String[10]
a[0] = "John";
a[1] = "Smilth";
a[2] = "Eric";
a[9] = "Howard";
// arrays start with zero, but 0 to 9 are also ten entries just
// like 1 to 10.
for (int j = 0; j <= a.length; j++)
    String tempString = a[j];
    // Here goes your other code
// I replaced i with j, because i surrounded by round brackets
// means printing text cursive on this BBS board

Similar Messages

  • Purpose of request.setAttribute(String parm1, Object parm2)

    HttpServletRequest request.setAttribute(String parm1, Object parm2) vs. HttpSession session.setAttribute(String parm1, Object parm2)
    hi
    can anybody please explain to me what does HttpServletRequest request.setAttribute() do? and for what purpose is it used for?
    i already know that HttpSession session.setAttribute(String parm1, Object parm2) is used to bind a session to a variable, so that it can be accessed throughout the servlet application.
    thanx
    shankha
    ps: please correct me if i'm wrong

    shankha,
    What does the API doco say?
    I think it just sets a request scoped attribute... ie a request parameter.
    This looks pertinant: http://www.rgagnon.com/javadetails/java-0401.html

  • Conver a string to object?

    hi, I am having problem converting string to object, then store the object into a object linklist node. I debugged it to make sure that everything the user types got stored in the string, but when the debug reaches "obj = temp;". obj doesn't have any value. why is that??
    String temp;
    Object obj;
    //have the user input something to the string. then...
    obj = temp;
    temp = (String) obj;
    ObjNode.insert(obj);
    Thank you...

    well, it's one of my assignment. have to write a class of object circular linked queue with a main funtion to test it. in the main function, I have to somehow store the object into the object node, but I havn't learned how to read object, only string. so I am tring to read string then change to object and store it. but if you could tell me how to just read object, it would be much easier for me.
    thank you.

  • Problems with String[] Class Object

    Hi guys,
    I'm writing a web server who should invoke a method of a class when asked by a client.
    My problem is that if the method that should be invoked has a String[] parameter the web server is unable to invoke it and throws a java.lang.IllegalArgumentException: argument type mismatch.
    Useful pieces of code to understand are the following:
    //create the Class[] to pass as parameter to the getMethod method
    Class[] paramType = {String[].class};
    //find the class "className" and create a new instance
    Class c = Class.forName(className);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(nameMeth, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);I've noted that System.out.println(theMethod); prints the signature of the method with the parameter type java.lang.String[].
    System.out.println(paramType[0]); instead prints [Ljava.lang.String;
    I know that [L means that it is an array, so why do you think that I'm having an argument type mismatch?
    Thank you                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I had no problems making that work.import java.lang.reflect.Method;
    public final class StringArray {
        public static final String CLASSNAME = "StringArray";
        public static final String METHODNAME = "myMethod";
        public static final String[] sa = { "a", "b"};
        // automatic no-args constructor
        public final void myMethod(String[] sa) {
            for(int i=0;i<sa.length;++i) {
                System.out.println(sa);
    public static final void main(String[] arg) throws Exception {
    //create the Class[] to pass as parameter to the getMethod method
    Object[] params = { sa };
    Class[] paramType = {sa.getClass()};
    //find the class "className" and create a new instance
    Class c = Class.forName(CLASSNAME);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(METHODNAME, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);

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

  • Using java type strings in objective C

    HI all,
    I am into a greater mess of creating a java equivalent string using NSString class. I need to a convert some strings into bytes and then I have to write in streams. The problem is in java the length of character is 2 bytes. But in objective C the length of char is 1 byte. In java they used to convert the the entire sting into char array and then the char array into byte array and then they write in the streams. I need to implement same as java. Using NSString , there are methods available to convert into NSData . from the object of NSData , the byte Array can be obtained. but the length of the byte array compared to the length of byte array in java seems to be half. I have used "NSUTF8StringEncoding" to encode the string into NSData. Is there anyway to obtain the above said scenario using objective C.
    Regards,
    Mohammed Sadiq.

    HI xnav,
    thanks a lot .. Following is my code :
    NSData *data = [@"12C58CE4DB9752C" dataUsingEncoding: NSUnicodeStringEncoding];
    int len = [data length];
    here the value of len is 32 bytes.
    anyway I didn't try out using CString.
    I also like to clarfiy the usage of unichar. Following is the code that i used to convert, to and from NSData using unichar :
    // converting to NSData
    +(NSData *)NSDataFromString:(NSString *)value_
    int len = [value_ length] * sizeof(unichar);
    unichar *buffer = (unichar *)malloc(len);
    [value_ getCharacters:buffer];
    NSData *data = [NSData dataWithBytes:buffer length:len];
    free(buffer);
    return data;
    // converting into NSString :
    +(NSString *)NSDataToString:(NSData *)data_
    unichar *characters = (unichar *)[data_ bytes];
    NSString *value = [NSString stringWithCharacters:characters length:[data_ length]];
    return value;
    I tried converting a sample string with above methods its working. shall i follow the above. does it affects any values that i used to fetch from the server.
    awaiting for your response
    Regards,
    Mohammed Sadiq.

  • Parsing a string to object attribute's

    My string will be delimited by tab spaces. I need to parse the contents of the string then assign these to the attributes on an object. The solution I believe would similar to this String to Vector method:
    public Vector stringParser(String inString) {
         //Local variables.
         int lastIndex = 0;
         Vector retVector = new Vector();     
         int theCount = 0;
         int indexOf = inString.indexOf( dConstants.DVX_CHAR_SEP );
         //Keep on looping until there are no more DVX_CHAR_SEP
         while( indexOf != -1 && lastIndex != indexOf ){
              retVector.addElement( new String( inString.substring( lastIndex, indexOf - 1 )));
              lastIndex = indexOf;
              indexOf = inString.indexOf( dConstants.DVX_CHAR_SEP, lastIndex + 1 );
         }//while there are DVX_CHAR_SEP's
         //The last bit of string will not be DVX_CHAR_SEP terminated. Grab it now.
         if( indexOf == -1 ){
         //Just in case there weren't any DVX_CHAR_SEP.
         indexOf = 0;
         retVector.addElement( new String( inString.substring( indexOf, inString.length()) ));
         return retVector;
    NB. public final char DVX_CHAR_SEP = '\t';

    And your question is...?
    (By the way, I generally use a StringTokenizer to do exactly that.)

  • String to Object, then get the Class

    hi I'm new in Java!
    what I want to do is to convert a String and convert it to a Object then get the classname of the Object.
    for example:
    ExampleClass classObject = new ExampleClass();
    String exampleString = "classObject";
    I want to convert the string "classObject" into an Object, then get the Class name of the Object. (Let's just say I don't know what the Class name is)

    static Class forName(String className)Please correct me if I'm wrong...
    but what I have is an Object name (in string format),
    not a Class Name.
    So I'm kinda looking for something like...
    static Object forName(String objectName)
    Class.forName() returns a Class object. From this you can create an instance.
         String s = "java.awt.Frame";
         java.awt.Frame frame = (java.awt.Frame) (Class.forName(s)).newInstance();

  • Text Field String to Object problem

    Hi,
    i am trying to search a vector called mainStaffDataBase for a staff members name, found by getName();
    Now thats all good an well, but here is the tricky part (for me)
    i have another vector called mainUnitDataBase, in which unit names are stored. To create a new unit, the constructor needs to be used liked this Unit(String unitName, Staff staffName);
    What i am trying to do is by searching the mainStaffDataBase for a staff member, to reference that staff member's object in creating the new unit.
    In the code: staff_field is the name of a text field which the user inputs the name which they wish to associate the unit with.
    This is the code i currently have.
    1. for (int i = 0; i < Uni.mainStaffDataBase.size(); i++){
    2. Staff staffMem = (Staff)Uni.mainStaffDataBase.elementAt(i);
    3. if (staff_field.equals(staffMem.getName())){
    4. staffMem = staff_field;
    5. }
    6. }
    7. Unit newUnit = new Unit(unit_field.getText(), staffMem);
    8. Uni.mainUnitDataBase.add(newUnit);
    The error i am getting is "incompatible types" on line 4.
    Im not too sure how to go about changing the name of the staff member because the constructor requires a Staff object be passed, and not a string.
    Any help would be much appreciated.
    cheers
    AnniHilatE
    Edited by: AnniHilatE on Oct 18, 2007 7:04 PM

    1) staffMem is a Staff object. staff_field is a String. You can't try to set one equal to the other.
    2) If staff_field.equals(staffMem.getName( )) you don't have to set staffMem = to anything. It already references the correct Staff object. You may want to set something else = to staffMem though, another Staff variable that is declared outside of the for loop. This is what you should use in your Unit initialization code.
    something like so:
            Staff staffFound = null;
            for (int i = 0; i < Uni.mainStaffDataBase.size(); i++)
                Staff staffMem = (Staff)Uni.mainStaffDataBase.elementAt(i);
                if (staff_field.equals(staffMem.getName()))
                    // staffMem already == the correct object. 
                    // now just have to be able to use it.
                    staffFound = staffMem; 
            if (staffFound != null)
                Uni.mainUnitDataBase.add(new Unit(unit_field.getText(), staffFound));
        Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
      // your code block goes here.
    &#91;/code&#93;

  • String in object name

    hi, wondering if someone can help me,
    i have some script in which the object name will be created
    from a string and now i need to call another object within the
    object and not sure how to do it.. here is some code:
    u will see on the first line of the code an object is
    duplicated with a new name
    and on the last line i need to change the value of an object
    within that new object i duplicated.. no i am not show how to do it
    with it's new object name, at the moment i just tried pic+i
    u see on the 2nd line i am able to do it because i am able to
    put the object path within " ".
    hope it not to confusing.

    Accessing pic+i+.button will act as variable. You need to
    Evaluate this using either a Square Bracket or evaluate function,
    See the below Code using the " [ ] " for evaluation

  • Unmarshalling from String to object

    Iam using castor API . I want to Unmarshall a string to an xml object . I saw the methods of castor. But was confused.
    Kindly help

    Me funciono colocando el progID de la interfaz que genero jawin en el constructor de la clase que se genero, despues utilice los metodos y fue transparente:
    Interfaz que genero jawin:::
    public interface CodeIMG {
    public static final GUID clsID = new GUID("{23435XCVDF2-6D62-6749- 8E00-00AS45GH87JU}");
    public static final String progID = new String("ActivexPDF.CodeIMG");
    la clase que genero jawin:::::::
    public class _CodeWER extends DispatchPtr {
    public int getTypeInfoToken() {
    return 0;
    static public final GUID proxyIID = new GUID("{632PHK77-6F0B-11D4-8PLD-00A024A31CC6}");
    static public final int iidToken;
    static {
    iidToken = IdentityManager.registerProxy(proxyIID, _CodeWER.class);
    public int getGuidToken() {
    return iidToken;
    * Creates empty _CodeWER Object
    public _CodeWER() throws COMException {
    super();
    * Creates _CodeWER() Object with progID
    public _CodeWER()(String progid) throws COMException {
    super(progid);
    * Queries interface of _CodeWER  Object
    public _CodeWER()(IUnknown other) throws COMException {
    super(other);
    * Creates _CodeWER() Object with CLSID
    public _CodeWER(GUID ClsID) throws COMException {
    super(ClsID);
    public boolean createImg(ObjectRef strChain, ObjectRef strFile) throws COMException {
    return ((java.lang.Boolean) invokeN("createImg", new Object[]{strChain, strFile}, 2)).booleanValue();
    Test de Prueba:::::::
    public class TestDLL implements CodeIMG {
         public static void main(String[] args) {
              try {
                   CodeWER pdf = new CodeWER ( clsID );               
                   boolean ok = pdf.createImg(new ObjectRef("9999999"), new ObjectRef("C:\\image.bmp") );
                   System.out.println("Lo generoi bien:: " + ok );
              } catch (COMException e) {
                   e.printStackTrace();
    Espero te sirva este ejemplito sencillo de jawin
    Saludos!!!!!!!!!!!!
    att juo

  • Using strings as objects

    hi.
    i get user input of type string but if the string is the same as the name of an object is there any way of using the methods within that object.
    for example
    class Object{
    String name, description;
    Object(String nameIn, String descriptionIn){
    name=nameIn;
    description=descriptionIn;
    void showDescription(){
    System.out.println(description);
    when i create a new object
    Object brick = new Object("brick", "it's hard");
    and i get user input of type String
    "brick"
    how would i get
    brick.showDescription();
    i didn't think this was possible so i created an array of Objects
    Object objectHolder = new Object[10];
    but i couldn't figure out how to add the Object to the array when it was being created.
    class Object{
    String name, description;
    static Object objectHolder = new Object[10];
    int store=0;
    Object(String nameIn, String descriptionIn){
    name=nameIn;
    description=descriptionIn;
    objectHolder[store] = Object // this doesn't work, i want it to be
    // the Object that is being created
    store = store + 1;
    then i can compare the String to each Object.name in the array to find the Object, and then get the Object.showDescription
    what do you think?
    also i would like to know how to add the object to the array as it is being created even if you think it is not a good way of doing it.
    thanks

    First off, never ever name your objects "Object", since that is very, very confusing. The reason for this is because ALL objects are derived from java.lang.Object, and the less ambiguity with that name the better.
    Now, let's look at your object. We'll call it "DungeonObject" for lack of a better name.
    The "objectHolder" should probably not actually be inside of DungeonObject. Instead, make it external to your object.
    Let's assume you have a container object called "Dungeon" which makes use of DungeonObjects.
    You could write the following for Dungeon:
    public class Dungeon {
      DungeonObject[] objectHolder;
      int nIndex;
      public Dungeon(int nObjectSize) {  // constructor
        objectHolder = new DungeonObject[nObjectSize];
        nIndex = 0;
      private boolean addObject(DungeonObject obj) {
        if (nIndex < objectHolder.length) {
          objectHolder[nIndex++] = obj;
          return true;
        return false;
      public boolean createObject(String name, String desc) {
        return addObject(new DungeonObject(name, desc));
    }When you want to create an object, use createObject.
    The DungeonObject it references could be defined as:
    public class DungeonObject {
      String m_name;
      String m_description;
      public DungeonObject(String name, String description) {
        m_name = name;
        m_description = description;
      // add gets and sets as described in previous post

  • Parse String to Object

    Hello,
    I passed an object as a parameter (in a url) in a jsp form to a servlet.
    As http only accepts text, the servlet gets the object as a String.
    How can I parse the info back to an object in the server side? Is that possible, anyway?
    Thanks,
    Al.

    You'd be better off assigning a unique id to the object, passing that unique id to the jsp, and using the unique id in the servlet to retrieve the object (obviously you'd have to store the object in a map whose key is the unique id).
    Sorry for saying unique so much.

  • C# SSIS Script component - Save List String to Object package-scope variable and read it in Script Task

    before posting this i was searching this on internet but was not able to find info regarding my specific case:
    i have a DataFlow Task with "Error output" pointing from FlatFile to
    Script Component that does below (variable "ErrorMessageList" is listed under ReadWriteVariables property):
    List<string> lsErrors = new List<string>();
    public override void Input0_ProcessInputRow(Input0Buffer Row)
    lsErrors.Add("test1");
    lsErrors.Add("test2");
        void PostExecute()
            base.PostExecute();
            Variables.ErrorMessageList = lsErrors;
    Then the DataFlow points to a ScriptComponent where this object variable is listed under ReadOnlyVariables property and does the below:
    public void Main()
    List<string> lsErrors = (List<string>)Dts.Variables["ErrorMessageList"].Value;
    and that is where i get exception-has-been-thrown-by-the-target-of-an-invocation
    What is wrong here?
    (i have mistakenly edited this first post before, so i tried to manually put it back to original version)

    i have missed the "override" keyword...
    public class ScriptMain : UserComponent
    public class UserComponent: ScriptComponent
    namespace Microsoft.SqlServer.Dts.Pipeline
    public class ScriptComponent
    // i should have seen this before
    public virtual void PostExecute();
    i believe i must have deleted the PostExecute method definition right after the ScriptComponent generated the script for me... and then when i've realized that i can't change ReadWriteVariables as a part of:
    public override void Input0_ProcessInputRow(Input0Buffer Row)
    // --- can't change ReadWriteVariables here
    then i had to add the method back but forgot that the base method is virtual
    thanks for this hint, Russ!

  • Compare 2 encrypted String Java Objects

    Hi,
    I am have encrypted the passwords of my change password page using the java.security.messagedigest API and stored in string object.
    Can any one pls tell me how to compare these 2 encrypted objects.
    Thanks
    Hem Pushap Kaushik

    Hi,
    Message Digest can be compared using
    boolean compare = java.security.MessageDigest.isEqual(byte[] digesta, byte[] digestb) ;hope this helps.
    Regards,
    Aparajith

Maybe you are looking for