Results 1 to 3 of 3
  1. #1
    viiids is offline Member
    Join Date
    Nov 2010
    Posts
    2
    Rep Power
    0

    Default Creating new object determining its type from a String

    I have the type of a variable stored in a String, for example :
    String s = "java.util.Date";
    Now i need to create an object whose type is denoted by s. Is there a way to get this done ?
    I tried using split on s to get the last String after '.' to check it with all primitive types and some basic advance types and then accordingly create an object however it seems that split will not work with '.'. I tried to use "\." but my code fails to compile. Please add your suggestions.

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    5

    Default

    Java Code:
    		String s = "java.util.Date"; 
    		Object o = Class.forName(s).newInstance();
    		if(o instanceof java.util.Date){
    			java.util.Date d = (java.util.Date)o;
    			System.out.println(d);
    		}
    ?

    are you sure, that you need somehting like that? sounds like a design fault :)

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    it seems that split will not work with '.'. I tried to use "\." but my code fails to compile.
    The backslash is an escape character both for regexes and for String literals. To end up with a regex that contains a quoted dot -- \. -- you need to escape the backslash in the String literal -- \\ -- so that has to be coded as \\.[code]String string = ...;
    String[] strings = string.split("\\,");]/code]
    to check it with all primitive types and some basic advance types and then accordingly create an object
    I agree with eRaaaa that this is almost certainly a faulty design. Would you like to explain your requirement (note: the requirement, not your thoughts on how to meet those requirements).

    db

Similar Threads

  1. using instanceof to get Object type and parent type?
    By xcallmejudasx in forum New To Java
    Replies: 2
    Last Post: 11-06-2008, 06:24 PM
  2. [SOLVED] Cast string type to int type
    By GilaMonster in forum New To Java
    Replies: 9
    Last Post: 09-17-2008, 10:43 AM
  3. Need help with creating array of type object
    By riz618 in forum New To Java
    Replies: 3
    Last Post: 01-29-2008, 06:14 AM
  4. How to cast an Object into a specific type (Integer/String) at runtime
    By mailtogagan@gmail.com in forum Advanced Java
    Replies: 2
    Last Post: 12-03-2007, 01:04 PM
  5. Creating object of Type Object class
    By venkatv in forum New To Java
    Replies: 3
    Last Post: 07-17-2007, 03:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •