Home | Gaming | Programming | Play Online | Contact | Keyword Query
Games++ Games & Game Programming

GAMES++
Games++ Home
Games++ Gaming
Games++ Programming
Beta Testing Games
Free Online Games
Hints & Cheats

BROWSER UTILITIES
E-mail This Page
Add to Favorites

SITE SEARCH

Web Games++

AFFILIATES
Cheat Codes
Trickster Wiki
Game Ratings
Gameboy Cheats
PlayStation Cheats
BlackBerry Games
Photoshop Tutorials
Illustrator Tutorials
ImageReady Tutorials

ADVERTISEMENT

ADVERTISEMENT

How To Create An Object From A String

Java How To: Source Code

import java.lang.reflect.*;

Class  [] classParm  = null;
Object [] objectParm = null;
         
try 
{
  String name = "com.rgagnon.MyClass";
  Class  cl   = Class.forName(name);

  java.lang.reflect.Constructor co = cl.getConstructor(classParm);

  return co.newInstance(objectParm);
}
catch (Exception e) 
{
  e.printStackTrace();
  return null;
}

Another example, but this time we are calling a method dynamically

public class Test 
{
   public static void main(String args[]) 
   {
      try 
      {
         String name = "java.lang.String";
         String methodName = "toLowerCase";

         // get String Class
         Class cl = Class.forName(name);

         // get the constructor  
         java.lang.reflect.Constructor constructor = 
            cl.getConstructor
            (
               new Class[] 
               {
                  Class.forName("java.lang.String")
               }
            );    

         // create an instance     
         Object invoker = constructor.newInstance
            (
               new String[] {"REAL'S HOWTO"}
            );
  
         // the method has no argument
         Class arguments[] = new Class[] { };

         // get the method
         java.lang.reflect.Method objMethod = cl.getMethod(methodName, arguments);
  
         // covert "REAL'S HOWTO" to "real's howto"
         Object result = objMethod.invoke(invoker, arguments);
         System.out.println(result);    
      } 
      catch (Exception e) 
      {
         e.printStackTrace();
      }
   }
}

Copyright © 1998-2007, Games++ All rights reserved. | Privacy Policy