Menu
Topics Index
...
`

Create Object Using Reflection - Java Example Program


Create Object Using Reflection
import java.lang.reflect.*;

class CreateObjectUsingReflection
{
        public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException
        {
            // Creating an object with default constructor
            Class studentClass = Class.forName("Student");
            Student rick = (Student) studentClass.newInstance();
            rick.name = "Rick";
            System.out.println(rick.name);
            // Creating an object with two strings constructor
            Class bookClass = Class.forName("Book");
            Constructor twoStringsConstructor = bookClass.getDeclaredConstructor(String.class, String.class);
            Book learn_java = (Book) twoStringsConstructor.newInstance("Learn Java Perfectly", "Merit Campus");
            System.out.println(learn_java.title + " with " + learn_java.author);
        }
}

class Student
{

    String name;
    int marks;
    char section;
}

class Book
{

    Book(String title, String author)
    {
        this.title = title;
        this.author = author;
    }

    String title;
    String author;
}
OUTPUT

Rick
Learn Java Perfectly with Merit Campus

DESCRIPTION

© meritcampus 2019

All Rights Reserved.

Open In App