• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[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]
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out the methods of java.lang.Class.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
  •  
    Rob Spoor
    Sheriff
    Posts: 22783
    131
    Eclipse IDE Spring VI Editor Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Marc, I think you misread. Kumar wants to call not the constructor without parameters, but one with.
     
    Bartender
    Posts: 5167
    11
    Netbeans IDE Opera Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    It would help if you were to PostRealCode and UseCodeTags.

    Check out the API for java.lang.reflect.Constructor<T>#newInstance(Object... initargs)
     
    Kumar Maddu
    Greenhorn
    Posts: 6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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();
    }
    }

    }
     
    Bartender
    Posts: 2700
    IntelliJ IDE Opera
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.
     
    Rob Spoor
    Sheriff
    Posts: 22783
    131
    Eclipse IDE Spring VI Editor Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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
    Bartender
    Posts: 2700
    IntelliJ IDE Opera
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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
    Posts: 6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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
    Bartender
    Posts: 2700
    IntelliJ IDE Opera
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Posts: 22783
    131
    Eclipse IDE Spring VI Editor Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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
    Posts: 6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Posts: 22783
    131
    Eclipse IDE Spring VI Editor Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    Bartender
    Posts: 2700
    IntelliJ IDE Opera
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I'm still curious why you would want this.
     
    Rob Spoor
    Sheriff
    Posts: 22783
    131
    Eclipse IDE Spring VI Editor Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    How about plugin based systems?
     
    Wouter Oet
    Bartender
    Posts: 2700
    IntelliJ IDE Opera
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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).
     
    Consider Paul's rocket mass heater.
    reply
      Bookmark Topic Watch Topic
    • New Topic