devxlogo

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.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Seven Service Boundary Mistakes That Create Technical Debt

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.