Java 反射、类对象

发布于 2024-12-18 13:47:29 字数 825 浏览 3 评论 0原文

我的目标是在命令行中读入我希望观察其信息的类的名称。当我在运行前知道类名时,就没有问题了。我似乎无法管理的是如何根据字符串输入创建类对象。

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();
        }


    }

}

main 方法中的 2 行注释显示了我过去在编译之前知道类名时所做的操作。以下未注释的行显示了我认为应该有效的内容,但我收到了 ClassNotFoundException。该类确实存在,所以我不确定我遇到了什么问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轮廓§ 2024-12-25 13:47:29

两个建议:

  1. 确保给它提供完全限定的名称(例如 "java.lang.Thread" 而不仅仅是 "Thread")。
  2. 确保编译后的类文件确实位于类路径中。

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.
还在原地等你 2024-12-25 13:47:29

Class.forName 是在运行时按名称加载类的正确方法。

要么你的论点是错误的,要么你的类不在类路径中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文