File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How to create object to a specific class by using its name as string variable with out using new. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to create object to a specific class by using its name as string variable with out using new." Watch "How to create object to a specific class by using its name as string variable with out using new." New topic
Author

How to create object to a specific class by using its name as string variable with out using new.

Kumar Maddu
Greenhorn

Joined: Sep 21, 2010
Posts: 6
[color=darkblue]I am using the following code but i am unable to invoke the parameterized constructor while creating the object using Class.forName().newInstance.

String className="com.test.pack"+"ClassName";
responder=(Responder)Class.forName(className).newInstance();

Please suggest me the way how to create a object by calling parameterised constructor using the className string variable.

Thanks In Advance[color=darkblue]


ALL IS WELL:
Kumar
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19783
    
  20

Check out the methods of java.lang.Class.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Welcome to the ranch!

What specific errors are you getting?

It's hard to say without more information, but if I were to guess...
  • One problem might be that you're using the literal "ClassName" rather than a variable, className.
  • Another problem might be that you need a dot (period) between "com.test.pack" and className.
  • Or it might be a classpath issue.


  • "We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
    sscce.org
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19783
        
      20

    Marc, I think you misread. Kumar wants to call not the constructor without parameters, but one with.
    Darryl Burke
    Bartender

    Joined: May 03, 2008
    Posts: 4664
        
        5

    It would help if you were to PostRealCode and UseCodeTags.

    Check out the API for java.lang.reflect.Constructor<T>#newInstance(Object... initargs)


    luck, db
    There are no new questions, but there may be new answers.
    Kumar Maddu
    Greenhorn

    Joined: Sep 21, 2010
    Posts: 6
    Darryl Burke wrote:It would help if you were to PostRealCode and UseCodeTags.

    Check out the API for java.lang.reflect.Constructor<T>#newInstance(Object... initargs)



    Hi Darry,

    Here i am posting my entire code Please guide me, how to call a parameterized constructor using newInstance.


    package com.test.core.java;
    interface InstanceTest{
    public String getValue();
    }

    public class NewInstanceTest implements InstanceTest {
    String value;
    //public NewInstanceTest(){} In my class no default constructor will be there.
    //The object should be created using parameterised constructor by passing value

    public NewInstanceTest(String value){
    this.value=value;
    System.out.println("arg is :"+value);
    }

    public String getValue(){
    return value;
    }

    public static void main(String args[]){
    String className="com.test.core.java.NewInstanceTest";
    //className will be change dynamically based on user input.
    try {
    InstanceTest instanceTest=(InstanceTest)Class.forName(className).newInstance();
    System.out.println("Value:"+instanceTest.getValue());
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }

    }
    Wouter Oet
    Saloon Keeper

    Joined: Oct 25, 2008
    Posts: 2700

    Why do you want to do this? Reflection is a complex concept, performance is worse in comparison with using constructors the normal way, it's certainly not beginning Java and these kinds of problems can usually be solved with a good architecture.


    "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
    Please correct my English.
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19783
        
      20

    Wouter Oet wrote:Why do you want to do this? Reflection is a complex concept, performance is worse in comparison with using constructors the normal way, it's certainly not beginning Java and these kinds of problems can usually be solved with a good architecture.

    Because the class depends on user input. If that's really necessary then reflection is the only way to go.

    Kumar,

    first of all, please UseCodeTags, as Darryl already asked you to. You can edit your post to add them.
    Secondly, you have already been given hints on how to do this. Darryl even mentioned the class and method to use. Combined with my advice to check out java.lang.Class you should be able to get an instance of Darryl's class.
    Wouter Oet
    Saloon Keeper

    Joined: Oct 25, 2008
    Posts: 2700

    Rob Prime wrote:Because the class depends on user input. If that's really necessary then reflection is the only way to go.

    Yeah but I want to know why he wants that so that maybe we can come up with another solution. Reflection is powerful stuff but it comes at a cost.
    Kumar Maddu
    Greenhorn

    Joined: Sep 21, 2010
    Posts: 6
    Rob Prime wrote:
    Wouter Oet wrote:Why do you want to do this? Reflection is a complex concept, performance is worse in comparison with using constructors the normal way, it's certainly not beginning Java and these kinds of problems can usually be solved with a good architecture.

    Because the class depends on user input. If that's really necessary then reflection is the only way to go.

    Kumar,

    first of all, please UseCodeTags, as Darryl already asked you to. You can edit your post to add them.
    Secondly, you have already been given hints on how to do this. Darryl even mentioned the class and method to use. Combined with my advice to check out java.lang.Class you should be able to get an instance of Darryl's class.



    Hi Rob,

    I gone through the APIs suggested by "DarryI" as well as Class API also,And i have written the code it is working fine.
    But i am facing a problem regarding warning messages.That is In the eclipse it is showing a warning message of unchecked type cast,But i am checking null using conditional operator if it not null then only i am type casting it.I have pasted working code(which contains warning messages).Can you please suggest how to make warning free code.Thanks in advance.



    package com.test.core.java;

    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;

    interface InstanceTest{
    public String getValue();
    }

    public class NewInstanceTest implements InstanceTest {
    String value;
    //public NewInstanceTest(){} In my class no default constructor will be there.
    //The object should be created using parameterised constructor by passing value

    public NewInstanceTest(String value){
    this.value=value;
    System.out.println("arg is :"+value);
    }

    public String getValue(){
    return value;
    }

    public static void main(String args[]){
    String className="com.test.core.java.NewInstanceTest";
    //className will be change dynamically based on user input.
    try {
    /*Class.forName(className);
    Constructor<NewInstanceTest> obj=
    InstanceTest instanceTest=(InstanceTest)Class.forName(className).newInstance();*/


    //I am getting the following warning message for below statement:
    //Type safety: Unchecked cast from Class<capture#2-of ?> to Class<InstanceTest>

    Class<InstanceTest> instanceClass =(Class.forName(className)!= null ? (Class<InstanceTest>)Class.forName(className)
    : null);
    String initArgs[]={"10"};
    Class[] initClassArgs= new Class[initArgs.length];
    for(int i=0;i<initArgs.length;i++){
    initClassArgs[0]=initArgs.getClass();
    }
    Constructor instanceConstructor =instanceClass.getConstructor(initClassArgs);
    InstanceTest newInstanceTest = (InstanceTest)instanceConstructor.newInstance(initArgs);
    System.out.println("Value:"+newInstanceTest.getValue());

    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (SecurityException e) {
    e.printStackTrace();
    } catch (NoSuchMethodException e) {
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    e.printStackTrace();
    }
    }
    }
    Wouter Oet
    Saloon Keeper

    Joined: Oct 25, 2008
    Posts: 2700

    Like Darryl and Rob already asked you: UseCodeTags!

    The warning comes from trying to cast Class<?> to Class<InstanceTest>.
    So use Class<?>. And by the way Class.forName doesn't return null and you for-loop is wrong.
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19783
        
      20

    Kumar Maddu wrote:

    Wait, what?? If Class.forName(className) (which indeed will never return null) is not null return Class.forName(className) otherwise return null? Why not directly say ?

    You already know which constructor you want to call, one that takes a String. So why not declare it like that?

    If this is how you are going to use reflection than I definitely agree with Wouter - you shouldn't.

    There are two ways of dealing with reflection:
    1) use reflection all the way, using getMethod etc.

    2) the preferred way: use reflection to load implementations of interfaces, or subclasses of abstract classes. For instance:
    With generics you will most definitely get a warning, but since this is a new object it's safe to use @SuppressWarnings("unchecked") to get rid of that.
    Kumar Maddu
    Greenhorn

    Joined: Sep 21, 2010
    Posts: 6
    Finally i got error free and warning free code.Thank you very much Rob , DaryI and Wouter for your guidence .
    I am placing the final version here
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19783
        
      20

    Now you've added code tags I finally see that you are actually using reflection in the second way I suggested. I really couldn't see the difference between the interface and the class without code tags.
    Wouter Oet
    Saloon Keeper

    Joined: Oct 25, 2008
    Posts: 2700

    I'm still curious why you would want this.
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19783
        
      20

    How about plugin based systems?
    Wouter Oet
    Saloon Keeper

    Joined: Oct 25, 2008
    Posts: 2700

    Then that would be a good answer. But since this is beginning Java I would like to know if the topic starter tries to solve a problem using reflection that could be easily be solved by a good architecture (and without much boilerplate code).
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: How to create object to a specific class by using its name as string variable with out using new.