3

My objective is to read in to the command line the name of a Class I wish to observe info on. When I know the class name before runtime, I have no issue. What I can't seem to manage is how to create a class object based on a string input.

public class Tester {

    static void methodInfo2(Object obj) throws ClassNotFoundException {
        //some stuff        
        System.out.print("Test!");

    }

    public static void main (String args[]) throws ClassNotFoundException{
        String className = args[0];
        System.out.println("Class:  "+className);

        //myclass2 mc = new myclass2();
        //Class c = mc.getClass();
        Class argClass = Class.forName(className);

        try {
            methodInfo2(argClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

}

The 2 commented out lines in the main method show what I have done in the past when I know the class name before I compile. The following uncommented line shows what I thought should work, but I receive a ClassNotFoundException. The class certainly exists so I'm not sure what problem I'm having.

Nibirue
  • 411
  • 1
  • 15
  • 29

2 Answers2

7

Two suggestions:

  1. Make sure you're giving it the fully-qualified name (e.g. "java.lang.Thread" and not just "Thread").
  2. Make sure the compiled class file is actually on the classpath.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Thanks for the fast reply! For those who find this topic later, my problem was the class I wanted I defined myself within a package in elcipse. The fix was to append the package name to the beginning of the class name: "packageName.myclass2" – Nibirue Nov 30 '11 at 15:22
2

Class.forName is the right way to load a class by name at runtime.

Either your argument is wrong or your class isn't in the classpath.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
wrschneider
  • 17,913
  • 16
  • 96
  • 176