Java反射,类对象 [英] Java Reflection, Class Objects

查看:156
本文介绍了Java反射,类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是读入命令行中我希望观察信息的类的名称。当我在运行时知道类名,我没有问题。我不能管理的是如何创建一个类对象基于字符串输入。

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


    }

}


b $ b

在main方法中注释掉的行显示了我在过去做什么,当我在编译之前知道类名。以下取消注释的行显示了我认为应该工作,但我收到一个ClassNotFoundException。该类肯定存在,所以我不知道我有什么问题。

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.

推荐答案

两个建议:


  1. 确保你给它的完全限定名(例如java.lang.Thread,而不只是Thread)。

  2. 确保编译的类文件实际位于类路径中。

  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.

这篇关于Java反射,类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆