Friday, 1 May 2015

newInstance() method (Reflection Session-2)

newInstance() method

The newInstance() method of Class class and Constructor class is used to create a new instance of the class.
The newInstance() method of Class class can invoke zero-argument constructor whereas newInstance() method of Constructor class can invoke any number of arguments. So Constructor class is preferred over Class class.

Syntax of newInstance() method of Class class

public T newInstance()throws InstantiationException,IllegalAccessException
Here T is the generic version. You can think it like Object class. You will learn about generics later.

Example of newInstance() method

Let's see the simple example to use newInstance() method.
1.    class Simple{  
2.     void message(){System.out.println("Hello Java");}  
3.    }  
4.      
5.    class Test{  
6.     public static void main(String args[]){  
7.      try{  
8.      Class c=Class.forName("Simple");  
9.      Simple s=(Simple)c.newInstance();  
10.   s.message();  
11.   
12.   }catch(Exception e){System.out.println(e);}  
13.   
14.  }  
15. }  

Output:Hello java

No comments:

Post a Comment

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...