Tuesday 31 October 2017

How to instantiating the objects using constructor object - Java Reflection | Reflection in java



Click here to watch in Youtube : 
https://www.youtube.com/watch?v=ynUvXxzWWgM&list=UUhwKlOVR041tngjerWxVccw

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

/**
 * 
 * Instantiating Objects using Constructor Object.
 *
 */
public class ReflectionDemo
{
    public static void main(String[] args)
    {
        try
        {

            Class classObj = String.class;
            /*
             * Parameters:
             * 
             * parameterTypes - the parameter array
             * 
             * Returns: the Constructor object of the public
             * constructor that matches the specified parameterTypes
             * 
             */

            Constructor constructor = classObj.getConstructor(StringBuffer.class);
            StringBuffer sb = new StringBuffer("Peter");
            /*
             * Returns:a new object created by calling the constructor
             * this object represents
             */
            String str = (String) constructor.newInstance(sb);
            System.out.println(str);
        }
        catch (NoSuchMethodException | SecurityException
                | InstantiationException | IllegalAccessException
                | IllegalArgumentException
                | InvocationTargetException e)
        {
            e.printStackTrace();
        }

    }

}
Output
Peter

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ReflectionDemo_cons_instantiate.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ReflectionDemo_cons_instantiate

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/eca56e82732b6bdecf5c1f7d98c23f5bc231a672/BasicJava/ReflectionDemo_cons_instantiate/?at=master

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment