How to create a new instance of a class from a string?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: How to create a new instance of a class from a string?

  1. #1
    Join Date
    Apr 2011
    Posts
    9

    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

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    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.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  3. #3
    Join Date
    Apr 2011
    Posts
    9

    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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center