• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding creation object Dynamically  RSS feed

 
raj talatam
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why it is not possible to create Object dynamically if the Class doesn't have

default constructor..

public class COne {

COne(int a){

}
}
public class MyApp {
public static void main(String args[]) {


Class c=Class.forName("COne");
c.newInstance();
}
}


Capture.PNG
[Thumbnail for Capture.PNG]
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All objects are created dynamically in Java. It's the only way to create them.

As for your question, you're basically asking "Why can't we use a constructor that doesn't exist?" When you call newInstance(), it invokes the no-arg constructor. If there is no such constructor, it fails, just as if you tried to do new X() when X doesn't have a no-arg constructor.

If you want to use reflection to instantiate an object using some other constructor, you can use the Class object to get the available Constructor objects, and invoke the appropriate one.
 
raj talatam
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeff Verdegan wrote:All objects are created dynamically in Java. It's the only way to create them.

As for your question, you're basically asking "Why can't we use a constructor that doesn't exist?" When you call newInstance(), it invokes the no-arg constructor. If there is no such constructor, it fails, just as if you tried to do new X() when X doesn't have a no-arg constructor.

If you want to use reflection to instantiate an object using some other constructor, you can use the Class object to get the available Constructor objects, and invoke the appropriate one.

can you please tell me how to use reflection for this problem...
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you come across the Reflection API tutorial trail? You can find examples there of how to do this.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!