import java.lang.reflect.Constructor; import java.lang.*; /** * A simple example of how to build new members of classes * "on the fly", given only the name of the class. Written as * an example for the FLIP programming team and updated for * the CS152 Options group. * * @author Samuel A. Rebelsky * @authro Wanlin Liu * @version 1.2 of November 1999 */ public class Classist { /** * Given the name of a class, build an object in that class * using the zeroary constructor for that class. Throws an * exception when one of the affiliated methods fails. */ public static Object buildOne(String className, String parameter) throws Exception { Class desiredClass; // Build the class for the given class name. desiredClass = Class.forName(className); Class[] paramType = {Class.forName("java.lang.String")}; Constructor cons = desiredClass.getConstructor(paramType); Object[] param = {parameter}; return cons.newInstance(param); } // buildOne(String) /** * Testing. Build one of each of the objects specified on the * command line and call their toString method. */ public static void main(String[] args) throws Exception { Name liu = new Name("Liu", "Diana", "Wanlin"); Object obj = buildOne("Name", liu.toString()); System.out.println("liu is: " + obj.toString()); System.out.println("A string is: " + buildOne("java.lang.String", "I am a string")); } // main(String[]) } // class Classist