Tuesday, 24 October 2017

How to create a new instance using newInstance method of class Object | Reflection in java


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

DisplayMessage.java
public class DisplayMessage
{
    public void sayHello()
    {
        System.out.println("Hello.......");
    }
}

ReflectionDemo.java
public class ReflectionDemo
{
    public static void main(String[] args)
    {

        try
        {
            Class<?> classObj = Class.forName("DisplayMessage");
            /*
             * Returns:a newly allocated instance of the class represented by
             * this object.
             */
            DisplayMessage displayMessage = (DisplayMessage) classObj.newInstance();
            displayMessage.sayHello();
        }
        catch (InstantiationException | IllegalAccessException
                | ClassNotFoundException e)
        {
            e.printStackTrace();
        }

    }

}
Output
Hello.......

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/921a65d57c0ec8a07d5edae78f1552619b89e108/BasicJava/ReflectionDemo_newInstance/?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