简体   繁体   中英

Java Reflection, Class Objects

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.

Two suggestions:

  1. Make sure you're giving it the fully-qualified name (eg "java.lang.Thread" and not just "Thread" ).
  2. Make sure the compiled class file is actually on the classpath.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM