Results 1 to 3 of 3
- 11-18-2010, 06:32 PM #1
Member
- Join Date
- Nov 2010
- Posts
- 2
- Rep Power
- 0
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.
- 11-18-2010, 06:42 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
?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 :)
- 11-19-2010, 06:18 AM #3
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 = ...;it seems that split will not work with '.'. I tried to use "\." but my code fails to compile.
String[] strings = string.split("\\,");]/code]
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).to check it with all primitive types and some basic advance types and then accordingly create an object
db
Similar Threads
-
using instanceof to get Object type and parent type?
By xcallmejudasx in forum New To JavaReplies: 2Last Post: 11-06-2008, 06:24 PM -
[SOLVED] Cast string type to int type
By GilaMonster in forum New To JavaReplies: 9Last Post: 09-17-2008, 10:43 AM -
Need help with creating array of type object
By riz618 in forum New To JavaReplies: 3Last Post: 01-29-2008, 06:14 AM -
How to cast an Object into a specific type (Integer/String) at runtime
By mailtogagan@gmail.com in forum Advanced JavaReplies: 2Last Post: 12-03-2007, 01:04 PM -
Creating object of Type Object class
By venkatv in forum New To JavaReplies: 3Last Post: 07-17-2007, 03:33 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks