Instantiation using Reflection

This lesson demonstrates how objects can be created using reflection.

We'll cover the following...

Question # 1

How can we create class instances using reflection?

There are two methods that can be invoked with appropriate parameters to instantiate class objects using reflection:

  • Constructor.newInstance()

  • Class.newInstance()

Using Constructor.newInstance

        Class<?> c = String.class;

        Constructor<?>[] ctrs = c.getConstructors();

        Constructor ctr = null;
        for (int i = 0; i < ctrs.length; i++) {
            if (ctrs[i].getParameterCount() == 1 &&
                ctrs[i].getParameterTypes()[0].getCanonicalName().equals("java.lang.String")) {
                ctr = ctrs[i];
                break;
            }
        }

        String myString = (String) ctr.newInstance("Educative");
        System.out.println(myString);

...