简体   繁体   English

Java反射,类对象

[英]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. main方法中的2个注释掉的行显示了我在编译之前知道类名的过去所做的事情。 The following uncommented line shows what I thought should work, but I receive a ClassNotFoundException. 以下未注释的行显示了我认为应该工作的内容,但是我收到了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" ). 确保你给它一个完全限定的名字(例如"java.lang.Thread"而不只是"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. Class.forName是在运行时按名称加载类的正确方法。

Either your argument is wrong or your class isn't in the classpath. 您的参数是错误的,或者您的类不在类路径中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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