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.

2 Answers 2

6

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.
Sign up to request clarification or add additional context in comments.

1 Comment

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"
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.