Java Reflection, Class Objects

2019-07-01 22:50发布

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条回答
该账号已被封号
2楼-- · 2019-07-01 23:14

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.

查看更多
冷血范
3楼-- · 2019-07-01 23:28

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.
查看更多
登录 后发表回答