dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java
Expertise: Advanced
Nov 18, 1998

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Reflecting on a Classy String

Java's reflection API allows the instantiation of an object using only its String description. A Java application can determine the class of an object from the associated string and then construct an instance of the class. For example:
  
  1. public Object getObject (){
  2. try {
  3. Class MyClass = Class.forName("Hello");
  4. Constructor con = MyClass.getConstructor(new Class[] {});
  5. Object myHello = con.newInstance(new Object[] {});
  6. return myHello;
  7. }
  8. catch (Exception e) {}
  9. }
On Line 3, the class corresponding to the string "Hello" is obtained by calling the method forName() on the Class (java.lang.Class) class and passing "Hello" as a string argument. Note that for this to work, Hello.class must be loadable by Java's ClassLoader; it should be accessible from the CLASSPATH set up for the runtime environment.

The next step, on Line 4, is to obtain the default constructor for the class Hello by calling the method getConstructor() on the Class variable MyClass and passing it a class object with null parameters. The syntax used here is for anonymous classes.

On Line 5, the object is created using the constructor obtained in the previous line. Finally, on Line 6, the newly instantiated object is returned. What you are seeing here is a rudimentary Object Factory.

Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date