-
May 2nd, 2011, 09:45 AM
#1
How to create a new instance of a class from a string?
Hello all.
I am quite new to java and i would like to know how i can create a new instance of a class from a string where the class name is held.
I'm more from a php background and i know that i can do
Code:
$var = 'classname';
new $var();
to create a new instance of it
Currently in my java i have if statements to check the string name and then i do
Code:
return new ClassName().Execute().toString();
I'm looking for a more efficient way of doing this than having a if statement for every request that i have
Many thanks in advance
-
May 2nd, 2011, 12:01 PM
#2
Re: How to create a new instance of a class from a string?
Look at the API docs for the java.lang.Class class.
To create an instance from a classname using the default constructor you can use:
Code:
Class myClass = Class.forName(myClassName);
obj = myClass.newInstance();
If you need to pass parameters into the constructor then use one of the getConstructor(s) methods to get the appropriate constructor and call its newInstance(...) method.
-
May 2nd, 2011, 01:03 PM
#3
Re: How to create a new instance of a class from a string?
Thanks for your response Keang i shall read the API docs and work with this code
Thanks for your time
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|