Monday, May 13, 2013

Java Reflection API: Constructing Objects


Moving forward from my previous article: Java Reflection API: Introduction

Using Java Reflection API, you can instantiate objects at runtime and invoke class constructors.
Getting Constructor
To get the list of all public constructors declared use the below code:
Constructor[]
constructors = mClass.getConstructors();

Here Constructor[] is an array of type java.lang.reflect.Constructor. However If you have the precise parameter types of the constructor you want to access, you can do so rather than obtain the array all constructors. Below example returns the public constructor of the given class which takes String as parameter:
Constructor constructor
= mClass.getConstructor(new Class[]{String.class});

Further to read all the input parameters of a constructor, do like this:
Class[] parameterTypes =
constructor.getParameterTypes();

Do the below to create an object using Java Reflection:
Constructor constructor = mClass.getConstructor(String.class);
Object mObject = constructor.newInstance("argument-1");
Next post in the series is Java Reflection API: Calling Methods

No comments:

Post a Comment