Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Reflect No Argument Constructor Example

Related Tutorials


 
 

Share on Google+Share on Google+

No Argument Constructor Example

Advertisement
In this section you will learn how to know that whether any class consists No-Argument Constructor or not ?. Here is an example that provides the usage of the newInstance() method in more detail.

No Argument Constructor Example

     

In this section you will learn how to know that whether any class consists No-Argument Constructor or not ?. Here is an example that provides the usage of the newInstance() method in more detail.

Here in our example we have used "forName()" static method of Class and then we have invoked newInstance() method to create a new object without any argument. Invoking newInstance() method throws a NoSuchMethodException if the class does not have any no-argument constructor.

Here is code for example:

 

 

 

NoArgConstructor.java

import java.lang.reflect.*;
import java.util.ArrayList;

public class NoArgConstructor {
  public static void main(String str[]){
  try{
 ArrayList list = (ArrayList)
   (
Class.forName("java.util.ArrayList").newInstance());
 System.out.println("No-Argument Constructor exist.");
 System.out.println("New Object created Successfully");
  }catch(Exception e){
  System.out.println("No-argument constructor does not exist.");
  System.out.println(e.getMessage());
  }
 }
}

Output:

Download Source code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 10, 2008

Related Tutorials

Discuss: No Argument Constructor Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com